Monday, December 21, 2009

Constructor in java

When you create a new instance (a new object) of a class using the new keyword, a constructor for that class is called. Constructors are used to initialize the instance variables (fields) of an object. Constructors are similar to methods, but with some important differences.

Static in java

Static Members
Static members are those that belong to a class as a whole and not to a particular instance (object). A static variable is initialized when the class is loaded. Similarly, a class can have static methods. Static variables and static methods are collectively known as static members, and are declared with a keyword static. Static members in the class can be accessed either by using the class name or by using the object reference, but instance members can only be accessed via object references.

Constants
  Static variables are quite rare. However, static constants are more common. For example, the Math class defines a static constant:
public class Math
{
. . .
   public static final double PI = 3.14159265358979323846;
. . .
}
You can access this constant in your programs as Math.PI.

If the keyword static had been omitted, then PI would have been an instance field of the Math class. That is, you would need an object of the Math class to access PI, and every Math object would have its own copy of PI.

Another static constant that you have used many times is System.out. It is declared in the System class as:
public class System
{
. . .
   public static final PrintStream out = . . .;
. . .
}

As we mentioned several times, it is never a good idea to have public fields, because everyone can modify them. However, public constants (that is, final fields) are ok. Because out has been declared as final, you cannot reassign another print stream to it:
System.out = new PrintStream(. . .); // ERROR--out is final

NOTE:
If you look at the System class, you will notice a method setOut that lets you set System.out to a different stream. You may wonder how that method can change the value of a final variable. However, the setOut method is a native method, not implemented in the Java programming language. Native methods can bypass the access control mechanisms of the Java language. This is a very unusual workaround that you should not emulate in your own programs.

Static Methods
Static methods are methods that do not operate on objects. For example, the pow method of the Math class is a static method. The expression:
Math.pow(x, a)

computes the power x^a. It does not use any Math object to carry out its task. In other words, it has no implicit parameter.

You can think of static methods as methods that don't have a this parameter. (In a non-static method, the this parameter refers to the implicit parameter of the method)

Because static methods don't operate on objects, you cannot access instance fields from a static method. But static methods can access the static fields in their class. Here is an example of such a static method:

public static int getNextId()
{
   return nextId; // returns static field
}

To call this method, you supply the name of the class:
int n = Employee.getNextId();

Could you have omitted the keyword static for this method?
Yes, but then you would need to have an object reference of type Employee to invoke the method.

NOTE :
It is legal to use an object to call a static method. For example, if harry is an Employee object, then you can call harry.getNextId() instead of Employee.getnextId(). However, we find that notation confusing. The getNextId method doesn't look at harry at all to compute the result. We recommend that you use class names, not objects, to invoke static methods.

You use static methods in two situations:
• When a method doesn't need to access the object state because all needed parameters are supplied as explicit parameters (example: Math.pow)
• When a method only needs to access static fields of the class (example: Employee.getNextId).

Also see difference between java and c++ static.
Points to note about static.




Tuesday, December 15, 2009

Nesting of classes : Introduction

It is possible to define a class within another class; such classes are known as nested classes.

The scope of a nested class is bounded by the scope of its enclosing class. Also a nested class has access to the members, including private members, of the class in which it is nested. However, the
enclosing class does not have access to the members of the nested class.

Consider the case that class B is defined within class A. So it means:
  • B is known to A, but not outside of A. 
  • B as has access to A's members, including private members.
See types of nested classes .

    Abstract classes

    As seen from the previous example, the superclass is more general than its subclass(es). The superclass contains elements and properties common to all of the subclasses. The previous example was of a concrete superclass that instance objects can be created from. Often, the superclass will be set up as an abstract class which does not allow objects of its prototype to be created. In this case, only objects of the subclass are used. To do this the reserved word abstract is included in the class definition.
    Abstract methods are methods with no body specification. Subclasses must provide the method statements for their particular meaning. If the method was one provided by the superclass, it would require overriding in each subclass. And if one forgot to override, the applied method statements may be inappropriate.

    public abstract class Animal  // class is abstract
    {
      private String name;
      public Animal(String nm)      // constructor method
      { name=nm; }
      public String getName()       // regular method
      { return (name); }
      public abstract void speak(); // abstract method - note no {}
    }


    Abstract classes and methods force prototype standards to be followed (ie. they provide templates).
    See also - Abstract classes : cpp vs java

    Sunday, December 13, 2009

    Access modifiers in Java

    Access modifiers specifies who can access them. There are four access modifiers used in java. They are :
    • public
    • private
    • protected
    • no modifer (declaring without an access modifer). Using ‘no modifier’ is also sometimes referred as ‘package-private’ or ‘default’ or ‘friendly’ access.
    Usage of these access modifiers is restricted to two levels. The two levels are class level access modifiers and member level access modifiers.

    I) Class level access modifiers (java classes only)

    Only two access modifiers is allowed, public and no modifier
    • If a class is ‘public’, then it CAN be accessed from ANYWHERE.
    • If a class has ‘no modifer’, then it CAN ONLY be accessed from ‘same package’.

    II) Member level access modifiers (java variables and java methods)

    All the four public, private, protected and no modifer is allowed.
    • public and no modifier – the same way as used in class level.
    • private – members CAN ONLY access.
    • protected – CAN be accessed from ‘same package’ and a subclass existing in any package can access.
    Understanding by the table below

    For better understanding, member level access is formulated as a table:

    Access Modifiers

    Same Class Same Package Subclass Other packages
    public Y Y Y Y
    protected Y Y Y N
    no access modifier Y Y N N
    private Y N N N

    First row {public Y Y Y Y} should be interpreted as:

    • Y – A member declared with ‘public’ access modifier CAN be accessed by the members of the ‘same class’.
    • Y – A member declared with ‘public’ access modifier CAN be accessed by the members of the ‘same package’.
    • Y – A member declared with ‘public’ access modifier CAN be accessed by the members of the ‘subclass’.
    • Y – A member declared as ‘public’ CAN be accessed from ‘Other packages’.

    Second row {protected Y Y Y N} should be interpreted as:

    • Y – A member declared with ‘protected’ access modifier CAN be accessed by the members of the ‘same class’.
    • Y – A member declared with ‘protected’ access modifier CAN be accessed by the members of the ‘same package’.
    • Y – A member declared with ‘protected’ access modifier CAN be accessed by the members of the ‘subclass’.
    • N – A member declared with ‘protected’ access modifier CANNOT be accessed by the members of the ‘Other package’.

    similarly interpret the access modifiers table for the third (no access modifier) and fourth (private access modifier) records.

    Examples
    Public Members:
    For a subclass, if a member of its superclass is declared public, the subclass inherits that member regardless of whether both classes are in the same package.

    package pack1;
    public class Parent {
    public String getName() {
    return “Parent”;
    }
    }

    package pack2;
    Import pack1.Parent;
    Public class Child extends Parent{
    Public String getParentsName() {
    return getName();
    }
    }

    If you see the example above, the child class is able to access the parent class’s method getName() even without instantiating an object of the parent because it inherits the Parent class and all its method as part of the inheritance (extends) feature.

    Private Members:
    Members marked private can’t be accessed by code in any class other than the class in which the private member was declared. Let’s make a small change to the Parent class from an earlier example.

    package pack1;
    public class Parent {
    private String getName() {
    return “Parent”;
    }
    }

    Now the getName() method is private and is not visible from within the Child class and the same piece of code would throw up the below compilation error when you try to compile the class.

    cannot find symbol
    symbol : method getName()
    This error method looks as if the method getName() does not exist at all. Of course the method exists but unfortunately it is declared private and hence no class (except the class that has the exact code written into it) can access it. This includes a child class that extends the parent class that has the method.
    Note: You can write a method inside the child class that has the same name as the private method in the parent. This does not account as Overriding because the parent class method is not even visible and hence it is just another method and is not considered overriding.

    Tip: Though you may feel that public is better because all other classes can access your methods, that is seldom the case because a code that is visible to all other classes is not secure and that is not the best way to write your code. It is always best to provide just the appropriate level of access to methods and variables instead of having all of them public.

    Protected and Default Members:
    The protected and default access control levels are almost identical, but with one critical difference. A default member may be accessed only if the class accessing the member belongs to the same package, whereas a protected member can be accessed (through inheritance) by a subclass even if the subclass is in a different package.
    Take a look at the following two classes:

    package certification;
    public class ClassOne {
    void testIt() { // No modifier means method has default access
    System.out.println("ClassOne");
    }
    }

    In another source code file you have the following:

    package otherCertification;
    import certification.ClassOne;
    class ClassTwo {
    static public void main(String[] args) {
    ClassOne o = new ClassOne();
    o.testIt();
    }
    }

    As you can see, the testIt() method in the first file has default (think: package-level) access. Notice also that class OtherClass is in a different package from the AccessClass. When you compile the ClassTwo.java file you will get an error like below:
    No method matching testIt() found in class
    certification.ClassOne.o.testIt();
    From the preceding results, you can see that AccessClass can’t use the OtherClass method testIt() because testIt() has default access, and AccessClass is not in the same package as OtherClass. So AccessClass can’t see it, the compiler complains.
    Default and protected behavior differs only when we talk about subclasses. If the protected keyword is used to define a member, any subclass of the class declaring the member can access it through inheritance. It doesn’t matter if the superclass and subclass are in different packages, the protected superclass member is still visible to the subclass. This is in contrast to the default behavior, which doesn’t allow a subclass to access a superclass member unless the subclass is in the same package as the superclass. (See the example above)
    Whereas default access doesn’t extend any special consideration to subclasses, the protected modifier respects the parent-child relationship, even when the child class moves away (and joins a new package). So, when you think of default access, think of package restrictions. No exceptions at all. But when you think protected, think package + kids. A class with a protected member is marking that member as having package-level access for all classes, but with a special exception for subclasses outside the package.


    Tip: Remember that Default and Protected access is the same as long as inheritance is not involved.


    Local Variables and Access Modifiers

    Can access modifiers be applied to local variables? A BIG NO!
    There is never a case where an access modifier can be applied to a local variable, so watch out for code like the following:


    class Test {
    void doTest() {
    private int x = 7; //Not Possible
    this.doSomethingElse(x);
    }
    }

    The above code will not compile or run. Dont think that the private keyword is legal inside the method doTest().
    You can be certain that any local variable declared with an access modifier will not compile. In fact, there is only one modifier that can ever be applied to local variables—final.


     


     

    Functions or Methods in java

    Class behaviour are represented in Java by methods. To declare a method use the following syntax:
    [ "public" | "private" | "protected" ] [ "final" ]
    [ "static" | "abstract" | "native" ]
      return_data_type method_name "(" parameter_list ")"
      "{"
      // some defining actions
      "}"
    Accessibility keywords are the same as for properties. The default (ie. omitted) is package (aka friendly) or visible within the current package only.
    static methods are shared by all members and exist for all runtime. Static methods can be referenced without creating an instance of the class. abstract methods must be redefined on inheritance. native methods are written in C but accessible from Java.
    The return_data_type defines the type of value that the calling routine receives from the object (the reply message in object terminology). It can be any of the primitive types or the reserved word void (default value) if no message is to be returned. The statement return varName; is used to declare the value to be returned to the calling routine.
    The parameter_list can contain from zero to many entries of datatype varName pairs. Entries are separated by commas. Parameters are passed by value, thus upholding the encapsulation principle by not allowing unexpected changes or side effects. Object references (such as arrays) can also be passed.
    Some examples of method header parameter lists are:
     
    public static void example1() {}
    public static int add2(int x) {x+=2; return x;}
    public static double example3(int x, double d) {return x*d;}
    public static void example4(int x, int y, boolean flag) {}
    public static void example5(int arr[]) {} // note: this is object

    Note: Differences from cpp 
    Types of methods
    Pass by value or reference 

    Object references in java


    Those readers familiar with C/C++ have probably noticed that object references appear
    to be similar to pointers. This suspicion is, essentially, correct. An object reference is
    similar to a memory pointer. The main difference—and the key to Java’s safety—is that
    you cannot manipulate references as you can actual pointers. Thus, you cannot cause an
    object reference to point to an arbitrary memory location or manipulate it like an integer.



    The new operator dynamically allocates memory for an object. It has
    this general form:
    class-var = new classname( );
    Here, class-var is a variable of the class type being created. The classname is the name of
    the class that is being instantiated. The class name followed by parentheses specifies the
    constructor for the class.




    Assigning Object Reference Variables

    Box b1 = new Box();
    Box b2 = b1;



    b1 and b2 will

    both refer to the same object.







    Box b1 = new Box();
    Box b2 = b1;
    // ...
    b1 = null;
    Here, b1 has been set to null, but b2 still points to the original object.
    Note : When you assign one object reference variable to another object reference variable, you
    are not creating a copy of the object, you are only making a copy of the reference.

    this - same as cpp



    Garbage Collection
    Since objects are dynamically allocated by using the new operator, you might be
    wondering how such objects are destroyed and their memory released for later
    reallocation. In some languages, such as C++, dynamically allocated objects must
    be manually released by use of a delete operator. Java takes a different approach; it
    handles deallocation for you automatically. The technique that accomplishes this is
    called garbage collection. It works like this: when no references to an object exist, that
    object is assumed to be no longer needed, and the memory occupied by the object can
    be reclaimed. There is no explicit need to destroy objects as in C++. Garbage collection
    only occurs sporadically (if at all) during the execution of your program. It will not
    occur simply because one or more objects exist that are no longer used. Furthermore,
    different Java run-time implementations will take varying approaches to garbage
    collection, but for the most part, you should not have to think about it while writing
    your programs.







    The finalize( ) Method
    Sometimes an object will need to perform some action when it is destroyed. For
    example, if an object is holding some non-Java resource such as a file handle or
    window character font, then you might want to make sure these resources are freed
    before an object is destroyed. To handle such situations, Java provides a mechanism

    called finalization. By using finalization, you can define specific actions that will occur
    when an object is just about to be reclaimed by the garbage collector.

    To add a finalizer to a class, you simply define the finalize( ) method. The Java run
    time calls that method whenever it is about to recycle an object of that class. Inside the
    finalize( ) method you will specify those actions that must be performed before an
    object is destroyed. The garbage collector runs periodically, checking for objects that
    are no longer referenced by any running state or indirectly through other referenced
    objects. Right before an asset is freed, the Java run time calls the finalize( ) method on
    the object.
    The finalize( ) method has this general form:
    protected void finalize( )
    {
    // finalization code here
    }
    Here, the keyword protected is a specifier that prevents access to finalize( ) by code
    defined outside its class. This and the other access specifiers are explained in Chapter 7.
    It is important to understand that finalize( ) is only called just prior to garbage
    collection. It is not called when an object goes out-of-scope, for example. This means
    that you cannot know when—or even if—finalize( ) will be executed. Therefore, your
    program should provide other means of releasing system resources, etc., used by the
    object. It must not rely on finalize( ) for normal program operation.
    If you are familiar with C++, then you know that C++ allows you to define a destructor
    for a class, which is called when an object goes out-of-scope. Java does not support this
    idea or provide for destructors. The finalize( ) method only approximates the function
    of a destructor. As you get more experienced with Java, you will see that the need for
    destructor functions is minimal because of Java’s garbage collection subsystem.

    Some Java FAQs

    Q:
    What is the difference between an Interface and an Abstract class?
    A:
    An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
    .





    Q:
    What is the purpose of garbage collection in Java, and when is it used?
    A:
    The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.




    Q:
    Describe synchronization in respect to multithreading.
    A:
    With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors. 




    Q:
    Explain different way of using thread?
    A:
    The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.




    Q:
    What are pass by reference and passby value?
    A:
    Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed. 




    Q:
    What is HashMap and Map?
    A:
    Map is Interface and Hashmap is class that implements that.





    Q:
    Difference between HashMap and HashTable?
    A:
    The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.




    Q:
    Difference between Vector and ArrayList?
    A:
    Vector is synchronized whereas arraylist is not.




    Q:
    Difference between Swing and Awt?
    A:
    AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.




    Q:
    What is the difference between a constructor and a method?
    A:
    A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
    A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.





    Q:
    What is an Iterator?
    A:
    Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.




    Q:
    State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.
    A:
    public : Public class is visible in other packages, field is visible everywhere (class must be public too)
    private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.
    protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
    default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package
    .




    Q:
    What is an abstract class?
    A:
    Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.
    A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.





    Q:
    What is static in java?
    A:
    Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.




    Q:
    What is final?
    A:
    A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).

    Java program without main

    You can write a runnable Java program which does not have main method at all. This can be done using the static block of the class.

    The reason this works is that static initialization blocks get executed as soon as the class is loaded, even before the main method is called. During run time JVM will search for the main method after exiting from this block. If it does not find the main method, it throws an exception. To avoid the exception System.exit(0); statement is used which terminates the program at the end of the static block itself.
    public class MainMethodNot {
       static
       {
          System.out.println("This java program have run without the run method");
          System.exit(0);
       }
    }
    

    Other method is using applet

    Chitika