It is a concept in java to achieve the Dynamic / Run-time polymorphism. It is the process of assigning sub-class object in super type reference later if needed that sub-class object can be type-caste into its super type. Dynamic dispatch can be achieved only with the instance member.

Important point regarding dynamic dispatch

1. If we are trying to access instance member with dynamic dispatch concept then it will access sub-class overridden method.

2. If we are trying to access static member with the dynamic dispatch concept then it will access super-class method as because compiler internally replace the super-class reference variable with its class name.

Example showing dynamic dispatch with instance and static method.

class B {

 public static void display(){
  System.out.println("super-class static method");
 }
 public void add(){
  System.out.println("super-class instance method");
 }
}

public class A extends B{
 
 public static void display(){
  System.out.println("sub-class static method");
 }
 public void add(){
  System.out.println("sub-class instance method");
 }
 
 public static void main(String[] args) throws Exception {
  
  B b = new A(); // Dynamic dispatch 
  b.display();  // Calling static method
  b.add();     // Calling instance method
 }

}

In the above code the statement B b = new A() is used to store sub-class in its super-class and tried to access static method " display " which will super-class display() method as because compiler internally convert the b.display() into B.display() but in case of instance it will access with the object only that's why it call the overridden method in sub-class. 

Note : The same will happen with the static and instance variable. With dynamic dispatch concept accessing static variable will access super-class static variable but accessing instance variable will access sub-class instance variable.  

Interface is a keyword in java and also a concept in java to over come the limitation of not supporting multiple inheritance by java. Now with the concept of interface we can have implement multiple interface full filing the concept of a " single class extending more than one class ". In the case of class we can extend only one but with the interface we can implement more than one interface.

Click here to know why java is not supporting multiple inheritance

Syntax to declare an interface :-
interface < interface_name > { }

Syntax to implement an interface :-
class < class_name > implements interface < interface_name > { }

Syntax to implement an interface :-
class < class_name > implements  interface < inter_nm1 >, < inter_nm2>......< inter_nmN > { }

Syntax to extending another interface :-
class < class_name > implements  interface extends < inter_nm1 >, < inter_nm2>......< inter_nmN > { }

Important point regarding interface in java

1. " interface " keyword is used to define any interface in java.

2. We have to use ' implement ' keyword for implementing an interface, extends cannot be used with interface. 

3. Possible to implement more than one interface with single class. 

4.  Interface are fully abstract class. So no need to make an interface as abstract as it is by-default " public abstract ".

5.  An interface can extends another interface but cannot extends/ implements another class. 

6. We cannot declare any instance member inside an interface as it is fully abstract. 

7. Variable declared inside an interface are by default - " public final static " or we can use these modifier explicitly also. 

8. We cannot declare a method as final and static in an interface.

9. We cannot use private , protected , transient and volatile keyword with the variable declared in an interface.

10. We cannot use synchronized and native with the method declared in an interface. 

11. Inner class in an interface are by-default " public static " .

12. We cannot define constructor, instance and static initialization block in an interface. 

13. By-default method declared in an interface are " public abstract " or we can use these keyword explicitly also. 

14. We cannot create an object of an interface as it is fully abstract class.  

15. " .class " file is generated by the compiler for every interfaces. 

Some of the important questions regarding interface with answer

Q1. Why we cannot define instance variable in an interface?
 --> Defining instance variable in an interface is restricted to save memory as because instance variable is inherited in its sub-class.

Now think if we have 3 interfaces(A, B and C)  and 1 class (D).
Interface B and C are extending A and Class D is implementing B and C. That means if declaring instance variable is allowed then for each instance variable as separate copy is also created in the interfaces B and C extending A and those copy are again copied to the class D. So we have many duplicate copies in the sub-classes.

For ex- Now if we have define 100 instance variable then it will create 100 copy in B and 100 in C and finally class D contain total of 100+ 100= 200 unnecessary copy which will obviously take memory as it an instance variable.
So to solve this problem declaring instance variable is restricted instead static is allowed which will create one memory.  

Q2. Why we cannot define variable defined in an interface as private and protected ?
        There are two reason behind it :-

  1. It is because by-default it is using public so we cannot define both public and protected to a single variable. 
  2. As interface doesn't have any instance method implementation and we need to access private member with the help of any method as because we cannot create an object of an interface and with cannot directly access with the sub-class object so need some method implementation which is not possible.   

When we use an abstract modifier before the name of any user-define class then it is called as an abstract class. Abstract class in java has only method signature whose implementation must be in its sub-classes.

Important points regrading Abstract class

1. It cannot be instantiate means we cannot create object of an abstract class.
2. An abstract class can have instance member.
3. Abstract class doesn't have any method implementation instead can have only method declaration.
4. We cannot make an inner class as abstract.
5. We cannot use static method but can use static variable in the abstract class.
6. Extending abstract class means we need to override the abstract methods defined in the abstract class.
7. If we don't want to override abstract in its sub-class then declare that sub-class as abstract.
8. An abstract class may or may not have an abstract method.
9. Constructor of the abstract class will be used to instantiate the abstract class instance variable.
10. Overridden abstract class methods will be accessed by its sub-class object.
11. We can be able to create and reference variable for an abstract class.

Why we cannot instantiate an abstract class?
As because we are not implementing abstract method while declaring it in abstract class. So if an user have any chance to create an instance of abstract class means can able to call abstract method with that object but we don't have any body while declaring it in abstract so no need of calling an empty body method. That's why we are not allowed to create an instance of an abstract class.

If we are not allowed to create and instance of an abstract class then how it can have an instance variable?
We can be able to access instance member of any super-class with its sub-class object therefore we can be able to access the instance member of any abstract class with the object of its sub-class.

Who is responsible to initialize the instance member of abstract class and how?
Its obvious that constructor is always responsible to initialize any instance member of any class. Here by creating its sub-class object will call its constructor and with the super implementation in it, will be able to class its super-class constructor i.e abstract class constructor and finally that constructor is responsible to initialize its instance member.

Why we cannot use static keyword with the abstract method?
By using static keyword with the abstract method will make it eligible to call it with its class name but no need of calling an empty body method. So it is restricted to use static with the abstract method.

Why we need to override abstract method in its sub-class?
It is because an user can be able to call abstract method with its sub-class object so we need to override so that it will call an overridden implemented method.

What will happened if we are extending an abstract class with another abstract class?
Then no need to override the abstract method in its sub-class because sub-class itself is an abstract class.

Why we can create an reference variable of an abstract class?
It is because creating an reference variable doesn't instantiate the member of the abstract class and hence contain null means not referring any object.

Use of an abstract class

1. When we have only static member in our class which can able be accessed with its class name so no need of creating object unnecessarily.So for restricting user to create an object declare that class as abstract.

2. It is used to when the user want to have their own implementation. So declaring a method as abstract will give a chance to an user to have their own implementation for same method name.

An example showing an abstract class with some valid and invalid statement.

abstract class A{

 static int x;                 // valid
 int y;                       // valid
 abstract void add();         // valid
 static abstract void sub(); // invalid as static is not allowed.
}
public class E extends A {

 void add(){}       //Compulsory to override abstract method 
 
 public static void main(String[] args) {
  E e = new E();
  System.out.println(A.x);
  A a = new A();        // Invalid 
 }
}
Abstract is a keyword in java. So its a reserved word in java. general meaning of abstract is to hide the implementation, only show the outer structure. Now in computer science its meaning is that user can have their own implementation with abstract method.

Where we can use abstract keyword ?
Abstract can be used with class and method.

By using abstract with the method a user can able to have their own implementation according to their wish. Its the facility given by the java vendor to the user to have their own implementation.

Abstract with class

Using abstract modifier before the class name can make a class as abstract. Making a class as abstract means we cannot instantiate that class.

Syntax :

abstract  < access_modifier > class < class_name > {  } 

< access_modifier > --> Only public is used with abstract . Private and protected are not used.

To know more about abstract class Click here !

Abstract with method

Declaring abstract modifier with the method name will make that method as abstract. An abstract method cannot have their implementation where it is declared, it must be override in its sub-classes.

Syntax :

abstract  < access_modifier > < return_type > < method_name > {  } 

< access_modifier > --> Only public and protected are used. Private cannot be used with it.


Access Modifiers in java

Like public and private, protected is also a access modifier which has different visibility scope and it is also one of the keyword in java. Its scope are valid to the other packages but it should be within the sub-class. Like private we can be able to use protected scope with the constructor, methods, variables and inner classes. Accessing protected member outside its scope will give compilation error saying " Not Visible ".

Note : We cannot use protected with the class.

What are the possible areas where protected  members can be used ?
It can be used with constructor, methods, variables and inner classes.

Members of the class declared as protected can be accessible outside the package but with the current sub-class object in the other packages. We have two scopes in java:
1. Class Scope

  • Sub-class in the same package        --> Visible 
  • Sub-class in other packages            --> Visible 
  • Another class in the same package --> Visible 
  • Non- subclass in other package      --> Not visible 
2. Package Scope
  • Within the same package ---> Visible 
  • Outside the package         ---> Visible but in the current sub-class. 
Protected with Constructor 
Declaring protected keyword before the name of constructor will make it protected. Protected constructor of a class are visible in another class sub-class which is defined in another package and can only be accessible with that sub-class object. For ex-

D.java in com package 
------------------------------

package com;

public class D {

 protected D(){}  // Protected constructor 
 public static void main(String[] args) {
  
 }
}

E.java in def package
-----------------------------

package def;
import com.D;

public class E extends D {

 public static void main(String[] args) {

  E e = new E(); 
  D d = new D(); // " Visible "  
 }
}


Protected with variable
Like constructor variable declared as protected are also visible with the sub-class object in another package. For ex-

D.java in com package 
------------------------------

package com;

public class D {

 protected int x=10;  // Protected variable  
 public static void main(String[] args) {
  
 }
}

E.java in def package
-----------------------------

package def;
import com.D;

public class E extends D {

 public static void main(String[] args) {

  E e = new E(); 
  System.out.println(e.x); 
  D d = new D();
  System.out.pritln(d.x); // "Visible"
 }
}


Protected with the method
Like variable method declared as protected can be accessed with the sub-class object defined in another package. For ex-


D.java in com package 
-----------------------------

package com;

public class D {

 protected void display(){
             System.out.println("protected method");
 }                                           // Protected method
 public static void main(String[] args) {
  
 }
}

E.java in def package
----------------------------

package def;
import com.D;

public class E extends D {

 public static void main(String[] args) {

  E e = new E(); // Current class object
  e.display();  
 }
}


Private is the keyword in java and it is also called as the access modifier in java which defines the visibility to the members of the class like methods, constructors, variables etc. Declaring private to the members of the class will limit theirs visibility to that class only. If we are trying to access any private member in another class then compiler will give compilation error as " Member are not visible ".  

Note : We cannot use private with the class as it makes no sense making a class visible because we are accessing member of the class not the class itself. So we can be able to use private with the member of the class member.

Where we can be able to use private access modifier ?
Private access modifier can be used with the constructor, variable and methods.

Members of the class declared as private can be accessible within that class only. We have two scope in java program :-
1. Class Scope
  • Sub-class in the same package       --> Private is Not Visible .
  • Sub-class in different package        --> Private is Not Visible.
  • Another class in the same package --> Private is Not Visible.
  • Same class in the same package     --> Private is Visible.
2. Package Scope
  • Within the same package -- > Private is Not Visible. 
  • Outside the package        ---> Private is Not Visible. 
Private with constructor 

To make a constructor as private we have to use private keyword before the constructor. Declaring super-class constructor as private will restrict to create an object of super-class in sub-class as private members are not accessible outside its scope. For ex-

public class prog{

    private prog(){}

}

class A extends prog {

      public static void main(String arg[]){

      prog p= new prog(); //Cannot create object as constructor 
                            is declared as private. 
    }
}

Private with variable

Like private constructor , variable can be declared as private and cannot be accessible in sub-class or any other class expect in the class in which it is declared as private. For ex-

public class prog{

     private int x=10;
}

class A extends prog {

     public static void main(String arg[]){

       prog p= new prog();
       System.out.println(x); //not visible as 'x' is declare 
                                as private.
     }
}

Private with methods

Using private keyword before the name of the constructor makes it a private method and has accessibility limit to that class only and hence accessioning outside the class will give compilation error. For ex-

public class prog{

     private void display(){}

}

class A extends prog {

    public static void main(String arg[]){

      prog p= new prog();
      p.display();   //Compilation error as display()is private. 
   }
}

As its name ' public ' itself indicates that any member of the class declared as public will be visible and accessible ANYWHERE. We have two scope in java programs :
1. Class scope
  • Sub-class in the same package       --> Public is visible .
  • Sub-class in different package        --> Public is visible.
  • Another class in the same package --> Public is visible.
  • Same class in the same package     --> Public is visible.
2. Package Scope
  • Within the same package -- > Public is visible. 
  • Outside the package       ---> Public is visible. 
So public members are visible EVERYWHERE and can be accessible form ANYWHERE.

Where and how we can use public access modifier in java ?
--> Public can be used with class, interface, constructor and variables.

Public with class 
If we are not using any access modifier with the class name then by default it is declared as ' default ' and declaring default will restrict its accessibility to the same package only. So to make any class visible to the another package we have to use public with the class. For ex-

public class prog { }

The above class is now visible to the other packages as well. 

Public with constructor
By default constructor is using default keyword before its name whose visibility will be limited to that package only in which class is been defined. If we want to access that constructor through another class which is defined in another package then we need to define the constructor as public to have its visibility to the other packages as well in which that is been imported. For ex-

Let suppose there are two class A and B in different packages com and def respectively and we import class A using import statement in def package where class B is defined to access the class A constructor by creating the object of class A. Now we came across few cases :

1. EXPLICIT CONSTRUCTOR : - If in com package any explicit constructor is there which is by default ' default ' and then if we try to create class A object in class B then it will compilation error that " constructor is not visible ".

2. NO EXPLICIT CONSTRUCTOR :- If we are not defining any constructor explicitly then JVM will invoke by default constructor and place public keyword before the constructor and hence it won't give any compilation error.

3. PUBLIC EXPLICIT CONSTRUCTOR :-  And if we are declaring constructor explicitly as public then it work fine and won't give and any compilation error.

Public with variable
Like constructor we can also use public keyword with class variable but not with the local variables as their scope will be within the method or constructor block only. Non-public members give compilation error " not visible ". Defining public with the class variables means that it can be accessible in the class which is defined in other package. for ex-

Let suppose there are two class and B in different packages com and def respectively and we import class A using import statement in def package where class B is defined to access the class A variables by creating the object of class A. like -

A.java in com package
------------------------------
package com;

public class A {

public int z=30;   // public variable.
int y=20;         // Be default ' default ' variable. 

 public A(){

  System.out.println(y);
  System.out.println(z);
 }
 public static void main(String sush[]) { }

}

B.java in def package
------------------------------
package def;
import com.A;

public class B{

 public static void main(String sush[]) {

     B b = new B();  // Class B object.
     A a = new A();  // Class A object.

  System.out.println(a.z);  //compiler successfully as it is 
                              declared public in class A.

  System.out.println(a.y);  // As y is not public so 
                              compilation error.
 }
}

Public with interfaces
Using public keyword before the interface will make it visible to any classes in any packages. If we are not using any public then it will not be visible to other packages and hence no class can be able to implement that interface. Without using public to the interface if we try to import that that interface it will give compilation error as " not visible " . for ex-

Let suppose there are two java files and B in different packages com and def respectively where are A.java contain an interface and B.java contain a java class B. We are importing interface A using import statement in def package where class B is defined to implement that interface using implements keyword. for ex-

A.java in com package
------------------------------
package com;

public interface A{

 void display();  // It is By default public and abstract.
}

B.java in def package
------------------------------
package def;
import com.A;  //No compilation error as interface is public

public class B implements A{

 public void display(){
  System.out.println("Display() method");
 }

 public static void main(String sush[]) {

  B b = new B();
  b.display();  
 }
}

The above program compile and execute successfully as because we are importing public interface A.If we are not using any public keyword then it will give compilation error while importing interface as " not visible " .

Note: In a same program we cannot have both public interface and public class as because we are writing java file name as the public class name. So having two public in a single file compiler will instruct to have other public as the java file name.


Access Modifier in java defines the scope of accessibility of methods, constructors, variables etc. So to access the different members of the class/interfaces with different scope we have three access modifiers :

1. Public   --> Defines visibility everywhere        
     
2. Private   --> Defines visibility within the current class only    
   
3. Protected  --> Defines visibility within the same package and outside the package with
                          the object of the sub-class extending the class in another package. 

4. default --> Defines the visibility within the package only. 

Note: If we are not using any access modifier then by default the modifier will be " default " and explicitly we cannot use default as default is already a keyword in java.


Difference between access modifiers and modifiers 

Access modifier 
  • It defines the scope of visibility or accessibility of the members of the class.
  • Public, protected, private and default are the access modifiers used in java.
  • Except public and by default "default " modifier is used with the class .
  • We cannot use private and protected with the class.
  • It cab be at class or package level.

Modifiers 
  •  It provides the restriction to the methods and variables about its accessibility at the class level.
  • Static,final,abstract,synchronized, volatile are the modifiers used in java.
  • We cannot use static with the main class and hence can be used with inner class.
  • Final can be used with the class indicates that it cannot be extended by other classes.




Like other classes in java , anonymous is also a type of class but it doesn't have any name like other classes have their own name either defined by the user or pre-defined in the java by the java vendors. So anonymous class is defined as the class without name and it is defined by the user only.
No need of wonder that how a class can exist without any name ?
Its not that it doesn't have any name but generated by the compiler at the run-time. So user cannot guess what compiler will generate the name for an anonymous class. Due of this reason we cannot be define any constructor for the anonymous class. And this is the answer to the answer to the question why we cannot create an constructor of an anonymous class?

An anonymous will be defined dynamically by the { } after the constructor of the current class. Like this,
 new < constructor > { } ;

For every anonymous class a .class file will be generated like this,
< outer_class > $ < int_value > . class

< int_value > --> represents the number of times we are creating the anonymous class for the same outer class.

Anonymous class is always be the sub-class of the class/interface whose name is used while creating the anonymous class.  For ex-

public class prog{

public static void main(String[] args) {

 prog p = new prog(){};

 prog p1 = new prog(){}; 

     }
}

In the above program both the statement is going to create an anonymous class which is the sub-class of class prog. If you need any conformation for the point of sub-class then de-compile the .class generated for the anonymous class where you will find that

class prog$1 extends prog{ } --> For p object

class prog$2 extends prog{ } ---> For p1 object .

So from the above decompiled code we can confirm that anonymous class will act as the sub-class of the class through which it is created.

Important point regarding Anonymous class

1. We cannot create any constructor or reference variable for the anonymous class as we need to know class name for creating a constructor.

2. As it the sub-class of its super type so we can store its object reference to its super class reference.

3. We cannot create multiple object for the an anonymous class as because user doesn't know the name of the anonymous class.

4. Whenever we try to create another object with the new operator the compiler will create another class extending its super type.

5. If we are storing the sub-class reference to its super type reference then we can be able to access the super class inherited members.

6. If we are not storing the anonymous class object reference to its reference then we can be able to access only one member. for ex-

public class prog{

public static void main(String[] args) { 

 new prog(){

 void display() {

        System.out.println("Anonymous class method");
    } 

 }.display();
     }
}  

We can see that we can be able to access display method of the anonymous class, if other methods are defined then we cannot access if we are not storing the object reference to its super type.

7. To access the other member defined in the anonymous class which is the overridden method of its super type so we need to write the method signature to the super type then only we can access the method defined in the anonymous class with the super type object reference storing the anonymous class object reference. For ex-

public class prog{

void show(){}
void display(){}

public static void main(String[] args) {

 prog p = new pro(){

     void display(){
        System.out.println("Anonymous class method");
     }

     void show(){
        System.out.println("By Object Reference");
     }
 };

 p.show();
 p.display();

     }
}

So whenever there is the need of invoking multiple method we need to define the anonymous class method as the overridden method as because we cannot directly call two method with the object of the anonymous class. And we know that we can be able access single method at a time with the single object.  
Local inner class is a class which is define local to the outer class. So it must be defined within the local scope of a class like method, constructor or initialization block . A class within a class in never treated as the local inner class. And most importantly scope of the inner class will be limited to where it is declared, outside of which it is not valid. As local inner class is the local scope to the outer class then we all know that within a local scope we cannot define any static member. So here also in the local inner class we cannot define any static member.

For the local inner class a .class file is generated in the following format :

< outer_class > $ < int_value > < inner class > .class
where as int_value depends on the number of times inner class with the same name is used.

Important points regarding Local inner class

1. We cannot define any static member in a local inner class as because of local scope.

2. But static final variable can be used because of its constant nature.

3.  In the generated class file of local inner class the int value indicate that the local inner class has been used how many times in a single program with the same name.

4. We cannot use the local inner class with the same name in the same method, constructor or initialization block as like we cannot define local variable with the same name within the same block.

5. As we cannot define any static member so it cannot be the starting point of any java program.

6. We cannot create any object of local inner class outside the scope of that class.

Simple example to show the working of the local inner class :

public class prog{

    int x;                // Outer class instance member

prog(){                  //Outer class constructor

    class B {           // Local inner class 

         int x;        // Local inner class instance member

         B(){          // Local inner class constructor

               System.out.println("Local inner class");

           }
      }

     B b = new B();      // Local inner class object 

     class C{}          // Local inner class

   }

public static void main(String[] args) {

prog p = new prog();

     }
}

Like Instance inner class we have also static inner class. Static instance class is loaded at the time of loading the outer class as it is declared as static that means it will act as the static member of the outer class and hence we can be able to define static member as it get initialized at the time of loading the outer class.

Important point regarding Static inner class

1. We can be able to define static and instance both in the static inner class.

2. We can have main() method which will make static inner class possible to have starting point for any java program.

3.  It can be accessed from both static and instance scope of outer class.

4. ' this ' will always refer to the outer class member , to access inner class member we need to create inner class object.

5. As it a static class then we can be able to access the static member with the class name itself. Object will be needed to access instance member.

6. Inner class is extending Object class that means we cannot use outer class member with the help of inner class object.

Example showing the working of an static inner class

public class A{

   int x;        // instance member of outer class

static class B{     // inner static class

   B(){           // inner class constructor 

        System.out.println("Inner class constructor");
}

   int x;      // inner class instance member

   static int z=40;   // inner class static member

}


A(){                    // outer class constructor

    A.B a = new A.B();   // inner class object 

    a.x=30;

   System.out.println(a.x); 

   System.out.println(this.x);

   System.out.println(A.B.z); // Accessing inner class static 
                                with class name 

}

public static void main(String[] args) {

A p = new A();

A.B b = new A.B();     // inner class in static method 

Class c = b.getClass(); //getting class name of inner class

System.out.println(c.getName());

c=c.getSuperclass();  //getting superclass name of inner class

System.out.println(c.getName());

     }
}

As the name itself indicates that inner class with non-static scope that means a member of outer class which is of instance scope called as instance inner class. Instance inner class is itself a class but we cannot use any static member.

Why we cannot use any static member in instance inner class ?
--> It is first treated as the member of outer class. Because of this if it is declared as non-static that means JVM is not going to load the class while loading the outer class even if inner class is a class. So as the non-static member of outer class, at the time of class loading JVM will not be able to load the instance member and hence if JVM will not load it then no static member can be able to initialized at the class loading time and hence we cannot use any static member inside an instance inner class.

But can be able to define an static final variable as because it will be treated as constant. And there is no memory concern of final static variable hence we can use it uses directly the value instead through any variable.

We can define an instance member as it will be used when we are creating any object for instance inner class and hence there is no risk of declaring as instance memory for instance variable is not created at the time of class loading.

Important points regarding inner class.

1. To access inner class member we need to create an object of it as we cannot access it through outer class object.

2. Member of outer class cannot be accessed with the inner class object.

3. outer class member can be accessed directly with its name as internally this will be used to indicate current class object.

4. We cannot use any static member in the instance inner class.

5. Instance inner class cannot use be the starting point of any java program as we cannot use main() which is declared as static.

6. But we can be able to use static final member as it is always treated as constant an also it does not require any memory for its value storage.

What will happen if we try to use main() in instance inner class?
--> While compiling the java program it will gibe an compilation error as " inner class cannot have any static declarations ".

Is it possible to use instance inner class as the starting point of our program ?
--> No , as because we can't be able to use any static method inside instance inner class.

An example to show how to access to create an object and how to access the member of it .

public class A{

   int x;

class B{                           // instance inner class

    int x;                        // instance member of instance inner class.

   static final int z= 30;        // final static member

}

A(){                              // outer class constructor

   A.B a = new A.B();            // inner class object creation .

   a.x=30;                       // inner class instance member 
                                     initialization

   System.out.println(a.x);

   System.out.println(this.x);   // this refer to the outer 
                                    class instance member.

   System.out.println(a.z);     // accessing the static final 
                                   instance member.

}

public static void main(String[] args) {

 A p = new A();

     }
}

Inner class in a class defined as a class inside another class. So it is itself a class but first it will act as a member of that class. As we know that we cannot make a class as static but inner class can be made as static which proves that it is first a member of a class in which it is defined . We can execute our class with its name but to execute a inner class we need to take help of outer class that proves that an inner class has identity with its outer class.

Important points regarding Inner Class :

1. A .class file is generated  for inner class but the file name will be as follows :
    < outer_class_name > $ < inner_class_name > . class 

2. We can be able to create a reference of inner class within the scope of an outer class simply as a normal reference definition.

3. To create a reference of inner class outside the scope of an outer class then we need to indicate to write the inner class name followed by outer class name, like this
     < outer_class_name > . < inner_class_name > . < ref_value > = null ;

4. As inner class itself is a member of a outer class then it the other members won't be the member of the inner class.

5. We can have a class inside an inner class which is defined as the inner class of inner class.So like this we can have infinite number of inner class / nested classes.

6. Inner class is generally used for abstraction.

Example of an inner class :- 

class prog {    // main class 

int x;

class A {      // Inner class of prog 

int x ;
String name ;

public static void main( String sush[] ) {

System.out.println(" Inner class " ) ;
A a = new A();     // Object of an inner class 
  }

}

In the above example class A is an inner class of prog class which is also called as the instance class.

Types of Inner class :

There are four (4) types of inner class :

1. Instance inner class.  -->     Click here to know more about instance inner class
2. Static inner class.      -->     Click here to know more about Static inner class
3. Local Inner class       -->    Click here to know more about Local inner class
4. Anonymous inner class.


Like this in java one more most important keyword is there i.e super. super in Java has a wide use and it is mainly used to call the super class constructor explicitly by the user and implicitly used by the JVM to initialize the super class property.
Have you ever wondered that how super class members get instantiated by creating subclass object ?
Let suppose we have two class A and B following inheritance relation where B is extending A that means B is a sub-class and A is a super-class. Here if we create a sub-class object which is going to invoke the constructor of sub-class and then compiler will implicitly place super() to invoke the super-class constructor which is used to instantiate the super-class members.

Important points regarding super in java

1. If there are no constructor then a default constructor is invoke by the JVM to place a super() which will call the super-class constructor.

2. If we have any constructor with some implementation then also compiler will place one super() to call super-class constructor.

3. If we have a parameterized constructor and in which first statement is this( value ) , then it will recursively call the sub-class constructor and hence there will no chance to call super-class constructor. In this case compiler will give compilation error.

4. Always make sure that if a class in inheriting another class then there must  be a super() call through sub-class constructor either explicitly by the user or implicitly by the JVM to initialize the super-class property , otherwise compiler will give compilation error.

Important uses of super

1. It is used to initialize the super-class property by invoking super-class constructor from sub-class constructor.

2. Inherited members are accessible with the help of super.

3. If we have member defined in the sub-class and super-class with the same name then super is used to refer the super-class member where as this is used to refer current class member.

4. It is used to refer the member of current object which is inherited from super-class.

5. In a inheritance hierarchy at last super() is calling to object class constructor which indicates the end of calling super-class constructor.

An example to show how super is working

class A{

int x;   //super-class instance member

}

public class B extends A {

int x;       // sub-class instance member

B(int x){    //local variable x as an argument in constructor

System.out.println(x);     //x indicate local variable

System.out.println(this.x);  //this.x indicate current class 
                                instance member x

System.out.println(super.x); //super.x indicate current object 
                                having inherited member x .

}

public static void main(String sush[]) {

 B b = new B(10);

 }
}

In the above program every variable is having same name so in this case ,
1. If we write simply x then JVM will prefer local variable.
2. If we write this.x then JVM will search for any instance variable in the current class.
3. So to access the super class instance variable x we have to use super.

What if in the above program class A extends another class X then it will also have an instance variable x then how will access that member as super will only refer to its immediate super-class ?
--> To access the instance member x of class X we have to use the method which will return the value of x from class X. Using statement like super.super.x is invalid . for ex-

class X{

int x;           // instance member of class X

int value(){    // method returning x value of class X

this.x=40;     // initializing x to 40. 
return x;
    }
}

class A extends X{

int x;       // instance member of class A

}

public class B extends A {

int x;

B(int x){

System.out.println(x);

System.out.println(this.x);

System.out.println(super.x);

System.out.println(value());

}

public static void main(String[] args) {

 B b = new B(10);

 }
}



this is one of the most important keyword in java which refers to the current class object. Like we are creating an object for our class similarly internally a object is there called as this which points to the current class object unless we create an Object.We can say that  'this ' is not an actual object but it points to the current class object. Accessibility of ' this ' refers to the current object that means if we have more than one object in our class then this will refer to that object in which context area it is been used. 

Important points regarding this keyword 

1. It is a scope of instance context so it can only be used from the non-static context. 
2. It is an alias for the current object.
3. We can be able to assign this into other reference of the current or super class type. 
4. We cannot assign any other current class or its super class object in this as because it is defined as a final variable so content cannot be modified . 
5. ' this ' is a final variable so we cannot assign any reference. 

Some of the uses of this keyword 

1. this can be use to initialize the instance we have both local and instance member with same name.
2. this can be used to access the member from the current object.
3. this can be used while using constructor chaining i.e constructor overloading to pass the value from one overloaded constructor to another but it should be the first statement.
4. Also used to distinguish between the local variable and instance variable in any instance method . 

What if we try to access this from any static context ?
It will give an compilation error that " non-static variable this cannot be referenced from a static context " .

Why such type error occur and why we cannot access this in any static context ?
It is because static context is not a part of object and unless we create and object ' this ' cannot be used and hence we cannot guarantee that used will surely create an object in their program. That is why it is a compilation error as because compiler is very much unsure about the creation of object by the user.

Give an example showing the initializing the instance variable if local variable is of same name as of instance variable ?

public class prog {

int x ;           // Instance variable.

prog(int x) {    // In constructor parameter x is local.

this.x = x ;    //this.x is used to initialize instance var 
                 with local x. 
}
public static void main(String sush[]) {

 prog p = new prog(10);  // 10 is passed to x in constructor. 

 }
}

Give an example to show how it is been used in constructor chaining ?

public class prog {

int x ;          // instance variable.
int y ;          // Instance variable.

prog(int x){
this.x = x ;   //this.x is used to initialize instance var with 
                 local x i.e 30
}

prog(int x, int y) { 
this(30);       //30 is passed to one parameter overloaded 
                  constructor.

this.x = x ;   //this.x is used to initialize instance var 
                with local x i.e 10 
this.y = y ;   //this.y is used to initialize instance var 
                 with local y i.e 20
}

public static void main(String sush[]) {

 prog p = new prog(10,20);  // 10 is passed to x in constructor. 

 }
}

What will happen if we assign any other reference variable to ' this ' ?

If we try to assign any other current class reference or any super class reference to this variable then it will give compilation error that " cannot assign a value to final variable this " . It means it is a final variable we cannot modify the content of it. For ex -

public class prog {

int x ;           // Instance variable.

prog(int x) {  
prog p1 = new prog(); // Local object creation. 
this = p1;           // Assigning p1 to this "compilation error"
this.x = x ;        //this.x is used to initialize instance
                      var with local x. 
}
public static void main(String sush[]) {

 prog p = new prog(10);  // 10 is passed to x in constructor. 

 }
}

  1. Translating JSP to Servlet. (hello.jsp->hello_jsp.java)
  2. Compile the translated Servlet. (hello_jsp.java->hello_jsp.class)
  3. Loads the translated Servlet.
  4. Creates the instance of translated Servlet.
  5. Calls the life cycle method _jspInit().
  6. when user sends the request then container calls the life cycle method _jspService().
  7. At container shutdown time, containers call the _jspDestroy() method of life cycle.
You can find the translated Servlet and compiled classes in the folder Tomcat6.0\catlina\localhost\org\apache\jsp
Cache is representation of database near to application. when you cache the read-mostly(which will be repeatedly used) data, you can reduce the number of round trip between your application server and database server. Which increase performance of your application.

In general you can have three types of cache scope :
  1. Transactional scope cache.
  2. Process scope cache.
  3. Clustered scope cache.
1. Transactional scope cache : This kind of catch will be created whenever the transaction is started and run as long as transaction is running. Transactional scope cache will be destroyed whenever the transaction end either by commit or by rollback.
2. Process scope cache : This kind of cache can be accessed by multiple transaction running in the application or process.

3. Clustered scope cache : When your enterprise application is large scale application then you must use clustered environment where multiple server is clustered and integrated with LBS(load balancing server) for running the request. In clustered scope cache when one node caches the data then same data will also be replicated to other nodes automatically.
First Level Cache :
  • Session cache is first level cache.
  • Session cache is transnational cache.
  • Session cache is enabled by default and should not be disabled.
  • When ever you insert or update or select or delete the records then those persistence object will be placed automatically in session cache.
  • You can remove the persistence object from session cache using evict(obj)  and clear().
Second Level Cache :
  • Query cache is second level cache.
  • Query cache can be process scope and cluster scope cache.
  • Query cache is disabled by default. You have to enable explicitly if required.
  • When ever you execute the hibernate Queries HQL, QBC etc then all records returned by select statement will be placed in Query cache.
Steps to implements Query cache : 
  1. Enable the query cache by writing the following property in hibernate configuration doc.
    <property name="hibernate.cache.use_query_cache">true</property>
  2. Specify the required cache provider in hibernate configuration document.
    <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
    Note : Cache provider supported by hibernate
    ->HashtableCacheProvider
    ->EhCacheProvider
    ->OSCacheProvider
    ->SwarmCacheProvider
    ->TreeCacheProvider(jboss cache provider)
  3. Specify the required caching concurrency strategies in hibernate mapping doc.
    <cache usage="xx">
    here xx can be one of the following
    ->read-only
    ->nonstrict-read-write
    ->read-write
    ->transactional
    Note : You have to specify caching concurrency strategies separately for class, collections and Associations.
  4. call setCacheable() method with true value on query or criteria or SQLQuery objects.
    Query q=session.createQuery("from customer");
    q.setCachable(true);
    List list=q.list();
  5. Specify the storage implementations and Expiration policies
    Note : this will change from cache provider to provider.
Constructor is the member of the class and it has name same as class name. Constructor is the one of the important concept in java which is responsible to initialize the instance member of the class. Its functionality is like a method only  but used by the JVM as a indicator to initialize the instance variable. It is first invoked by JVM while creating the object of the user defined class. And to support inheritance it is calling super class constructor by invoking super() in the subclass constructor to initialize the property of super class. Constructor must not have any return statement as it is not going to return any value because by creating object it is automatically invoke by the JVM and used to initialize the property of the object whose reference value is stored in the reference variable so no need to return any value. 

If we have a constructor defined in our class then JVM is not going going to invoke any default constructor. Only the constructor defined by the user will be used to initialize the property of the object. 

The first statement for nay constructor must either be the this() or super(). Both cannot be used at the same time because this() is used to instruct for the current class and super() is used to instruct the super class. So both cannot used at a time as by invoking super(), the control will not be back to that position. 

Constructor can be overloaded which follows the chain of execution of overloaded constructor and finally make sure that at its last chaining, should call to super class constructor by invoking super(), may be implicitly by the JVM or explicitly by the user otherwise it will give error. 

As it is like a method so we can use throws keyword with it. 

Note : Try not to make any recursive constructor , by which JVM fails to invoke super() to initialize the super class member.And is there is no user defined super class then it will fail to invoke Object class to instruct JVM that , this is the end of the invoking super class constructor. 


What are the access specifier we can use with the constructor?
we can use public, private and protected with the constructor. 
--> public constructor is accessible anywhere.
--> private constructor is only accessible within that class only even it is inherited by the subclass.
--> protected constructor is accessible anywhere within the same package but outside the package it is only accessible to the sub-class which is extending the class which is present in the other package. 

Doesn't seems wonder that how a super class member get initialized by creating the object of the sub-class constructor ?
If we are simply creating the object of subclass then by default JVM will create a no-argument constructor in which super() is the first statement which is responsible for invoking the super-class constructor and that constructor is responsible for initializing the instance member of the super class before using it in sub-class. And finally the chain calling of the super-class constructor get stopped by invoking the Object class constructor which is the super class for all other class in java. 

Use of Constructor in Java
1. It is used to instantiate the instance member of the sub-class and super class instance member.
2. It is used to initialize the instance variable with user value passed at the time of object creation. 
3. It is used to invoke super class constructor by invoking the super(), which must be the first statement of any constructor. 

Some of the situation where compiler insert by default the super() explicitly of not implicitly implemented by the user. 

User defined code                                Compiler defined code 

1. Class A {                                               Class A {
   void A(){                                                 void A(){
    //statement                                               super();     // Inserted by compiler
        }                                                         //statement
    }                                                                }  }
                                                               
2. Class A{}                                              Class A{
                                                                  A(){
                                                                     super(); // Inserted by compiler. 
                                                                      } }

3. Class A {                                               Class A {
    A(int x ) {                                              A(int x ) {
    // statement                                              super() ; // Inserted by compiler
   }  }                                                          // statement        
                                                                  

Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic