Monday, February 11, 2013

What is final class in java?

In Java, a class organization such as:

        class A {}

        class B extends A {}

results in a superclass (A) and a subclass (B). References to B objects may be assigned to A references, and if an A reference "really" refers to a B, then B's methods will be called in preference to A's. All of this is a standard part of the object-oriented programming paradigm offered by Java.

But there is a way to modify this type of organization, by declaring a class to be final. If I say:

        final class A {}

then that means that A cannot be further extended or subclassed.

This feature has a couple of big implications. One is that it allows control over a class, so that no one can subclass the class and possibly introduce anomalous behavior. For example, java.lang.String is a final class. This means, for example, that I can't subclass String and provide my own length() method that does something very different from returning the string length.

There is also a big performance issue with final classes. If a class is final, then all of its methods are implicitly final as well, that is, the method is guaranteed not be overridden in any subclass. A Java compiler may be able to inline a final method. For example, this program:

        final class A {
                private int type;
                public int getType() {return type;}
        }

        public class test {
                public static void main(String args[])
                {
                        int N = 5000000;
                        int i = N;
                        int t = 0;
                        A aref = new A();
                        while (i-- > 0)
                                t = aref.getType();
                }
        }

runs about twice as fast when the class is declared final.

Of course, much of the time it's desirable to use the superclass / subclass paradigm to the full, and not worry about wringing out the last bit of speed. But sometimes you have heavily used methods that you'd like to have expanded inline, and a final class is one way of achieving that.

Friday, February 8, 2013

What is abstract class in Java?

What is abstract class in Java?

There are situations in which you will want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. That is, sometimes you will want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. Such a class determines the nature of the methods that the subclasses must implement. One way this situation can occur is when a superclass is unable to create a meaningful implementation for a method. This is the case with the class Figure used in the preceding example. The definition of area( ) is simply a placeholder. It will not compute and display the area of any type of object.

As you will see as you create your own class libraries, it is not uncommon for a method to have no meaningful definition in the context of its superclass. You can handle this situation two ways. One way, as shown in the previous example, is to simply have it report a warning message. While this approach can be useful in certain situations—such as debugging—it is not usually appropriate. You may have methods which must be overridden by the subclass in order for the subclass to have any meaning. Consider the class Triangle. It has no meaning if area( ) is not defined. In this case, you want some way to ensure that a subclass does, indeed, override all necessary methods. Java's solution to this problem is the abstract method.

You can require that certain methods be overridden by subclasses by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the superclass. Thus, a subclass must override them—it cannot simply use the version defined in the superclass. To declare an abstract method, use this general form:
abstract type name(parameter-list);

As you can see, no method body is present. Any class that contains one or more abstract methods must also be declared abstract. To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration. There can be no objects of an abstract class. That is, an abstract class cannot be directly instantiated with the new operator. Such objects would be useless, because an abstract class is not fully defined. Also, you cannot declare abstract constructors, or abstract static methods. Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or be itself declared abstract.
Here is a simple example of a class with an abstract method, followed by a class which implements that method:
// A Simple demonstration of abstract.
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.println("This is a concrete method.");
}
}

class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}

class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
}

Notice that no objects of class A are declared in the program. As mentioned, it is not possible to instantiate an abstract class. One other point: class A implements a concrete method called callmetoo( ). This is perfectly acceptable. Abstract classes can include as much implementation as they see fit.

Although abstract classes cannot be used to instantiate objects, they can be used to create object references, because Java's approach to run-time polymorphism is implemented through the use of superclass references. Thus, it must be possible to create a reference to an abstract class so that it can be used to point to a subclass object. You will see this feature put to use in the next example. Using an abstract class, you can improve the Figure class shown earlier. Since there is no meaningful concept of area for an undefined two-dimensional figure, the following version of the program declares area( ) as abstract inside Figure. This, of course, means that all classes derived from Figure must override area( ).
// Using abstract methods and classes.
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area();
}

class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}

class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}

class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}

As the comment inside main( ) indicates, it is no longer possible to declare objects of type Figure, since it is now abstract. And, all subclasses of Figure must override area( ). To prove this to yourself, try creating a subclass that does not override area( ). You will receive a compile-time error.

Although it is not possible to create an object of type Figure, you can create a reference variable of type Figure. The variable figref is declared as a reference to Figure, which means that it can be used to refer to an object of any class derived from Figure. As explained, it is through superclass reference variables that overridden methods are resolved at run time.

Wednesday, February 6, 2013

Access Modifiers in Java



Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are:

 Visible to the package. the default. No modifiers are needed.

 Visible to the class only (private).

 Visible to the world (public).

 Visible to the package and all subclasses (protected).
               
Default Access Modifier - No keyword:

Default Access Modifier - No keyword:

Default access modifier means we do not explicitly declare an access modifier for a class, field, method etc.
A variable or method declared without any access control modifier is available to any other class in the same package. The default modifier cannot be used for methods, fields in an interface.

Example:

Variables and methods can be declared without any modifiers, as in the following examples:
String version = "1.5.1";

boolean processOrder() {
   return true;
}

Private Access Modifier - private:

Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot be private.
Variables that are declared private can be accessed outside the class if public getter methods are present in the class.
Using the private modifier is the main way that an object encapsulates itself and hide data from the outside world.

Example:

The following class uses private access control:
public class Logger {
   private String format;
   public String getFormat() {
      return this.format;
   }
   public void setFormat(String format) {
      this.format = format;
   }
}
Here, the format variable of the Logger class is private, so there's no way for other classes to retrieve or set its value directly.
So to make this variable available to the outside world, we defined two public methods: getFormat(), which returns the value of format, and setFormat(String), which sets its value.

Public Access Modifier - public:

A class, method, constructor, interface etc declared public can be accessed from any other class. Therefore fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe.
However if the public class we are trying to access is in a different package, then the public class still need to be imported.
Because of class inheritance, all public methods and variables of a class are inherited by its subclasses.

Example:

The following function uses public access control:
public static void main(String[] arguments) {
   // ...
}
The main() method of an application has to be public. Otherwise, it could not be called by a Java interpreter (such as java) to run the class.

Protected Access Modifier - protected:

Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.
The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.
Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.

Example:

The following parent class uses protected access control, to allow its child class override openSpeaker() method:
class AudioPlayer {
   protected boolean openSpeaker(Speaker sp) {
      // implementation details
   }
}
 
class StreamingAudioPlayer {
   boolean openSpeaker(Speaker sp) {
      // implementation details
   }
}
Here if we define openSpeaker() method as private then it would not be accessible from any other class other than AudioPlayer. If we define it as public then it would become accessible to all the outside world. But our intension is to expose this method to its subclass only, thats why we used protected modifier.

Access Control and Inheritance:

The following rules for inherited methods are enforced:
·         Methods declared public in a superclass also must be public in all subclasses.
·         Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private.
·         Methods declared without access control (no modifier was used) can be declared more private in subclasses.
·         Methods declared private are not inherited at all, so there is no rule for them.



Monday, February 4, 2013

what is final keyword in java?

When you use the keyword ‘final’ with a variable declaration, the value stored inside that variable cannot be changed come what may!!

So suppose you do this :

final int i =10;

After this, nowhere in your code can you change the value of ‘i’ i.e. ‘i’ will always have a value ’10' .

So i = 11; //will give you a compile time error.

Now, suppose you did not initialize the final integer ‘i’ while declaring it.

final int i;

Can you assign any value to this variable now?

Yes, you definitely can. But only once!

So,

final int i;

i = 10; //This is fine

i = 11; //Compiler error

Now that was the core stuff about ‘final’ . Let’s learn a bit more in detail about it.

The ‘final’ keyword can be used for a class declaration or method declaration.

What happens when you use ‘final’ for a class declaration?

A: You cannot have a sub class of a class declared final i.e. No other class can extend this class.

What happens when you declare a method as final?

A: Simply put, the method cannot be overridden.

Can you override a method(Not declared as ‘final’) present inside a final class?

A: Obviously Not. Since there’s no way to extend a class declared final there’s no way of overriding its methods!

What happens when I declare a method inside a class as both ‘private’ and ‘final’ ?

A: Making a class both ‘private’ and ‘final’ makes the ‘final’ keyword redundant as a private method cannot be accessed in its sub class. But hey, you’ll be able to declare a method of the same name as in the base class if the method has been made private in the base class. But then that doesn’t mean you’re overriding the method. You’re simply declaring a new method in the sub class.

Note: You cannot make an ‘abstract’ class or method as ‘final’ because an ‘abstract’ class needs to be extended which will not be possible if you mark it as ‘final’!

What is static keyword in java?

static variable

    It is a variable which belongs to the class. 
    Static variables are initialized only once , at the start of the execution .
   These variables will be initialized first, before the initialization of any instance variables
    A single copy of static variable is shared  by all instances of the class
    A static variable can be accessed directly by the class name and does not  need any object
    Syntax : ClassName.StaticVariableName
  
   static method

    It is a method which belongs to the class and not to the object(instance)
    A static method can access only static data. It can not access non-static data (instance variables)
    A static method can call only other static methods and can not call a non-static method from it.
    A static method can be accessed directly by the class name and doesn’t need any object
    Syntax : ClassName.StaticMethodName
    A static method cannot refer to “this” or “super” keywords in anyway

    Side Note:

    main method is static , since it must be be accessible for an application to run , before any instantiation takes place.

static block

The static block, is a block of statement inside a Java class that will be executed when a class is first loaded in to the JVM
   
class Test{
 static {
 //Code goes here
 }
}

A static block helps to initialize the static data members, just like constructors help to initialize instance members


Friday, February 1, 2013

What is jvm.dll,java.exe and javaw.exe?

jvm.dll is the actual Windows implementation of the JVM (or better, the main entry point). C or C++ applications can use this DLL to run an embedded Java runtime, and that would allow the application to interface directly with the JVM, e.g. if they want to use Java for its GUI.

    java.exe is a wrapper around the DLL so that people can actually run Java classes without the need for a custom launcher application. It is a Win32 Console application, so Windows will open a fresh Command Prompt window if the exe is not run from a batch file.

    javaw.exe is a wrapper like java.exe, but it is a Win32 GUI application. Windows doesn't have to open a Command Prompt window, which is exactly what you want to run a GUI application which opens its own windows.

Why main method in java is static?

This is just convention. In fact, even the name main(), and the arguments passed in are purely convention.

When you run java.exe (or javaw.exe on Windows), what is really happening is a couple of Java Native Interface (JNI) calls. These calls load the DLL that is really the JVM (that's right - java.exe is NOT the JVM). JNI is the tool that we use when we have to bridge between the virtual machine world, and the world of C, C++, etc... The reverse is also true - it is not possible  to actually get a JVM running without using JNI.

Basically, java.exe is a super simple C application that parses the command line, creates a new String array in the JVM to hold those arguments, parses out the class name that you specified as containing main(), uses JNI calls to find the main() method itself, then invokes the main() method, passing in the newly created string array as a parameter. This is very, very much like what you do when you use reflection from Java - it just uses confusingly named native function calls instead.

It would be perfectly legal for you to write your own version of java.exe (the source is distributed with the JDK), and have it do something entirely different. In fact, that's exactly what we do with all of our Java based apps.

Each of our Java apps has its own launcher. We primarily do this so we get our own icon and process name, but it has come in handy in other situations where we want to do something besides the regular main() call to get things going (For example, in one case we are doing COM interoperability, and we actually pass a COM handle into main() instead of a string array).

So, long and short: the reason it is static is b/c that's convenient. The reason it's called 'main' is because it had to be something, and main() is what they did in the old days of C (and in those days, the name of the function was important). I suppose that java.exe could have allowed you to just specify a fully qualified main method name, instead of just the class (java com.myompany.Foo.someSpecialMain) - but that just makes it harder on IDEs to auto-detect the 'launchable' classes in a project.