Wednesday, 20 July 2016

java oops


Java static keyword
The static can be:
1.      variable (also known as class variable)
2.      method (also known as class method)
3.      block
4.      nested class
1) Java static variable
If you declare any variable as static, it is known static variable.
·        The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.
·        The static variable gets memory only once in class area at the time of class loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).
Understanding problem without static variable
class Student{  
     int rollno;  
     String name;  
     String college="ITS";  
}  
Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created.All student have its unique rollno and name so instance data member is good.Here, college refers to the common property of all objects.If we make it static,this field will get memory only once.
Java static property is shared to all objects.
Example of static variable
//Program of static variable  
  class Student8{  
   int rollno;  
   String name;  
   static String college ="ITS";  
  Student8(int r,String n){  
   rollno = r;  
   name = n;  
   }  
 void display (){System.out.println(rollno+" "+name+" "+college);}  
 public static void main(String args[]){  
 Student8 s1 = new Student8(111,"Karan");  
 Student8 s2 = new Student8(222,"Aryan");  
 s1.display();  
 s2.display();  
 }  
}  
Output:111 Karan ITS
       222 Aryan ITS















Program of counter without static variable
In this example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable, if it is incremented, it won't reflect to other objects. So each objects will have the value 1 in the count variable.
class Counter{  
int count=0;//will get memory when instance is created    
Counter(){  
count++;  
System.out.println(count);  
}    
public static void main(String args[]){  
Counter c1=new Counter();  
Counter c2=new Counter();  
Counter c3=new Counter();  
 }  
}  

Output:
1
1
1

Program of counter by static variable
As we have mentioned above, static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value.
class Counter2{  
static int count=0;//will get memory only once and retain its value  
  
Counter2(){  count++;  
System.out.println(count);  
}  
 public static void main(String args[]){  
 Counter2 c1=new Counter2();  
Counter2 c2=new Counter2();  
Counter2 c3=new Counter2();  
  }  
}  

Output:1
       2
       3



2) Java static method
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a class.
static method can access static data member and can change the value of it.
Example of static method
//Program of changing the common property of all objects(static field).  
  class Student9{  
     int rollno;  
     String name;  
     static String college = "ITS";  
       
     static void change(){  
     college = "BBDIT";  
     }  
   Student9(int r, String n){  
     rollno = r;  
     name = n;  
     }  
  void display (){System.out.println(rollno+" "+name+" "+college);}  
   public static void main(String args[]){  
    Student9.change();  
    Student9 s1 = new Student9 (111,"Karan");  
    Student9 s2 = new Student9 (222,"Aryan");  
    Student9 s3 = new Student9 (333,"Sonoo");  
    s1.display();  
    s2.display();  
    s3.display();  
    }  
}  

Output:111 Karan BBDIT
       222 Aryan BBDIT
       333 Sonoo BBDIT

Another example of static method that performs normal calculation
//Program to get cube of a given number by static method    
class Calculate{  
  static int cube(int x){  
  return x*x*x;  
  }  
  public static void main(String args[]){  
  int result=Calculate.cube(5);  
  System.out.println(result);  
  }  
}  

Output:125
Restrictions for static method
There are two main restrictions for the static method. They are:

1.      The static method can not use non static data member or call non-static method directly.
2.      this and super cannot be used in static context.
class A{  
 int a=40;//non static  
   
 public static void main(String args[]){  
  System.out.println(a);  
 }  
}        

Output:Compile Time Error

Q) why java main method is static?
Ans) because object is not required to call static method if it were non-static method, jvm create object first then call main() method that will lead the problem of extra memory allocation.

3) Java static block
Is used to initialize the static data member.
It is executed before main method at the time of classloading.
Example of static block
class A2{  
  static{System.out.println("static block is invoked");}  
  public static void main(String args[]){  
   System.out.println("Hello main");  
  }  
}  

Output:static block is invoked
       Hello main

Q) Can we execute a program without main() method?
Ans) Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.
class A3{  
  static{  
  System.out.println("static block is invoked");  
  System.exit(0);  
  }  
}  

Output:static block is invoked (if not JDK7)
In JDK7 and above, output will be:
Output:Error: Main method not found in class A3, please define the main method as:
public static void main(String[] args)


We would see following type of variables in Java:
  Local Variables
  Class Variables (Static Variables)
  Instance Variables (Non-static variables)

A class can contain any of the following variable types.
  Local  variables: Variables defined  inside  methods,  constructors  or  blocks  are  called  local  variables.  The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
  Instance variables: Instance variables are variables within a class but outside any method. These variables are  instantiated  when  the  class  is  loaded.  Instance  variables  can  be  accessed  from  inside  any  method, constructor or blocks of that particular class.
  Class  variables: Class  variables  are  variables  declared  within  a  class,  outside  any  method,  with  the  static keyword.


Constructors:
Every  class  has  a constructor. If we do not explicitly write a constructor for a class the Java compiler builds a default constructor for that class. Each time a new object is created, at least one constructor will be invoked. The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.
1.      Constructor name must be same as its class name
2.      Constructor must have no explicit return type

Types of java constructors
There are two types of constructors:
1.      Default constructor (no-arg constructor)
2.      Parameterized constructor

Default constructor: It is also known as no-arg constructor. Constructor with no arguments is known as default constructor.
It will be invoked at the time of object creation.
class Bike1{  
Bike1(){System.out.println("Bike is created");}  
public static void main(String args[]){  
Bike1 b=new Bike1();  
}  
}  
Parameterized constructor: Constructor with argument list is known as parameterized constructor.
class Demo
{
      public Demo(int num, String str)
      {
           System.out.println("This is a parameterized constructor");
      }
}

Java Copy Constructor
There is no copy constructor in java. But, we can copy the values of one object to another like copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
·        By constructor
·        By assigning the values of one object into another
·        By clone() method of Object class
In this example, we are going to copy the values of one object into another using java constructor.

class Student6{  
    int id;  
    String name;  
    Student6(int i,String n){  
    id = i;  
    name = n;  
    }  
      
    Student6(Student6 s){  
    id = s.id;  
    name =s.name;  
    }  
    void display(){System.out.println(id+" "+name);}  
   
    public static void main(String args[]){  
    Student6 s1 = new Student6(111,"Karan");  
    Student6 s2 = new Student6(s1);  
    s1.display();  
    s2.display();  
   }  
}  
Copying values without constructor
We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor.
class Student7{  
    int id;  
    String name;  
    Student7(int i,String n){  
    id = i;  
    name = n;  
    }  
    Student7(){}  
    void display(){System.out.println(id+" "+name);}  
   
    public static void main(String args[]){  
    Student7 s1 = new Student7(111,"Karan");  
    Student7 s2 = new Student7();  
    s2.id=s1.id;  
    s2.name=s1.name;  
    s1.display();  
    s2.display();  
   }  
}  
Constructor Chaining
Constructor chaining is nothing but a scenario where in one constructor calls the constructor of its super class implicitly or explicitly. Suppose there is a class which inherits another class, in this case if you create the object of child class then first super class(or parent class) constructor will be invoked and then child class constructor will be invoked.
Have a look at the below example –
class Human
{
        String s1, s2;
        public Human()
        {
              s1 ="Super class";
              s2 ="Parent class";
        }
        public Human(String str)
        {
               s1= str;
               s2= str;
        }
}
class Boy extends Human
{
        public Boy()
        {
              s2 ="Child class";
        }
        public void disp()
        {
               System.out.println("String 1 is: "+s1);
               System.out.println("String 2 is: "+s2);
        }
        public static void main(String args[])
        {
                Boy obj = new Boy();
                obj.disp();
        }
}
Output:
String 1 is: Super class
String 2 is: Child class
Explanation of above example:
Human is a super class of Boy class. In above program I have created an object of Boy class, As per the rule super class constructor (Human()) invoked first which set the s1 & s2 value, later child class constructor(Boy()) gets invoked, which overridden s2 value. 
------------------------------------------------------
------------------------------------------------------
 Method Overloading in Java
If a class have multiple methods by same name but different parameters, it is known as Method Overloading.
Different ways to overload the method
There are two ways to overload the method in java
1.      By changing number of arguments
2.      By changing the data type
In java, Methood Overloading is not possible by changing the return type of the method.
Singleton Classes
The Singleton's purpose is to control object creation, limiting the number of objects to one only. Since there is only one  Singleton  instance,  any  instance  fields  of  a  Singleton  will  occur  only  once  per  class,  just  like  static  fields.


this keyword in java
There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object.
Usage of java this keyword
Here is given the 6 usage of java this keyword.
·        this keyword can be used to refer current class instance variable.
·        this() can be used to invoke current class constructor.
·        this keyword can be used to invoke current class method (implicitly)
·        this can be passed as an argument in the method call.
·        this can be passed as argument in the constructor call.
·        this keyword can also be used to return the current class instance.






1) The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variable and parameter, this keyword resolves the problem of ambiguity.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the example given below:
class Student10{  
    int id;  
    String name;       
    Student10(int id,String name){  
    id = id;  
    name = name;  
    }  
    void display(){System.out.println(id+" "+name);}  
    public static void main(String args[]){  
    Student10 s1 = new Student10(111,"Karan");  
    Student10 s2 = new Student10(321,"Aryan");  
    s1.display();  
    s2.display();  
    }  
}  

Output:0 null
       0 null
In the above example, parameter (formal arguments) and instance variables are same that is why we are using this keyword to distinguish between local variable and instance variable.
Solution of the above problem by this keyword
//example of this keyword  
class Student11{  
    int id;  
    String name;  
    Student11(int id,String name){  
    this.id = id;  
    this.name = name;  
    }  
    void display(){System.out.println(id+" "+name);}  
    public static void main(String args[]){  
    Student11 s1 = new Student11(111,"Karan");  
    Student11 s2 = new Student11(222,"Aryan");  
    s1.display();  
    s2.display();  
}  
}  

Output111 Karan
       222 Aryan

If local variables(formal arguments) and instance variables are different, there is no need to use this keyword like in the following program:
Program where this keyword is not required
class Student12{  
    int id;  
    String name;  
      
    Student12(int i,String n){  
    id = i;  
    name = n;  
    }  
    void display(){System.out.println(id+" "+name);}  
    public static void main(String args[]){  
    Student12 e1 = new Student12(111,"karan");  
    Student12 e2 = new Student12(222,"Aryan");  
    e1.display();  
    e2.display();  
}  
}  

Output:111 Karan
       222 Aryan

2) this() can be used to invoked current class constructor.
The this() constructor call can be used to invoke the current class constructor (constructor chaining). This approach is better if you have many constructors in the class and want to reuse that constructor.
//Program of this() constructor call (constructor chaining)  
  
class Student13{  
    int id;  
    String name;  
    Student13(){System.out.println("default constructor is invoked");}    
    Student13(int id,String name){  
    this ();//it is used to invoked current class constructor.  
    this.id = id;  
    this.name = name;  
    }  
    void display(){System.out.println(id+" "+name);}     
    public static void main(String args[]){  
    Student13 e1 = new Student13(111,"karan");  
    Student13 e2 = new Student13(222,"Aryan");  
    e1.display();  
    e2.display();  
   }  
}  

Output:
       default constructor is invoked
       default constructor is invoked
       111 Karan
       222 Aryan
Where to use this() constructor call?
The this() constructor call should be used to reuse the constructor in the constructor. It maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see the example given below that displays the actual use of this keyword.
class Student14{  
    int id;  
    String name;  
    String city;  
      
    Student14(int id,String name){  
    this.id = id;  
    this.name = name;  
    }  
    Student14(int id,String name,String city){  
    this(id,name);//now no need to initialize id and name  
    this.city=city;  
    }  
    void display(){System.out.println(id+" "+name+" "+city);}  
      
    public static void main(String args[]){  
    Student14 e1 = new Student14(111,"karan");  
    Student14 e2 = new Student14(222,"Aryan","delhi");  
    e1.display();  
    e2.display();  
   }  
}  

Output:111 Karan null
       222 Aryan delhi
Rule: Call to this() must be the first statement in constructor.
class Student15{  
    int id;  
    String name;  
    Student15(){System.out.println("default constructor is invoked");}  
      
    Student15(int id,String name){  
    id = id;  
    name = name;  
    this ();//must be the first statement  
    }  
    void display(){System.out.println(id+" "+name);}  
      
    public static void main(String args[]){  
    Student15 e1 = new Student15(111,"karan");  
    Student15 e2 = new Student15(222,"Aryan");  
    e1.display();  
    e2.display();  
   }  
}  

Output:Compile Time Error


3)The this keyword can be used to invoke current class method (implicitly).
You may invoke the method of the current class by using the this keyword. If you don't use the this keyword, compiler automatically adds this keyword while invoking the method. Let's see the example



class S{  
  void m(){  
  System.out.println("method is invoked");  
  }  
  void n(){  
  this.m();//no need because compiler does it for you.  
  }  
  void p(){  
  n();//complier will add this to invoke n() method as this.n()  
  }  
  public static void main(String args[]){  
  S s1 = new S();  
  s1.p();  
  }  
}  

Output:method is invoked


4) this keyword can be passed as an argument in the method.
The this keyword can also be passed as an argument in the method. It is mainly used in the event handling. Let's see the example:
class S2{  
  void m(S2 obj){  
  System.out.println("method is invoked");  
  }  
  void p(){  
  m(this);  
  }  
    
  public static void main(String args[]){  
  S2 s1 = new S2();  
  s1.p();  
  }  
}  

Output:method is invoked
Application of this that can be passed as an argument:
In event handling (or) in a situation where we have to provide reference of a class to another one.




5) The this keyword can be passed as argument in the constructor call.
We can pass the this keyword in the constructor also. It is useful if we have to use one object in multiple classes. Let's see the example:
class B{  
  A4 obj;  
  B(A4 obj){  
    this.obj=obj;  
  }  
  void display(){  
    System.out.println(obj.data);//using data member of A4 class  
  }  
}  
  
class A4{  
  int data=10;  
  A4(){  
   B b=new B(this);  
   b.display();  
  }  
  public static void main(String args[]){  
   A4 a=new A4();  
  }  
}  

Output:10


6) The this keyword can be used to return current class instance.
We can return the this keyword as an statement from the method. In such case, return type of the method must be the class type (non-primitive). Let's see the example:
Syntax of this that can be returned as a statement
return_type method_name(){  
return this;  
}  
Example of this keyword that you return as a statement from the method
class A{  
A getA(){  
return this;  
}  
void msg(){System.out.println("Hello java");}  
}  
  
class Test1{  
public static void main(String args[]){  
new A().getA().msg();  
}  
}  

Output:Hello java


Proving this keyword
Let's prove that this keyword refers to the current class instance variable. In this program, we are printing the reference variable and this, output of both variables are same.
class A5{  
void m(){  
System.out.println(this);//prints same reference ID  
}  
  
public static void main(String args[]){  
A5 obj=new A5();  
System.out.println(obj);//prints the reference ID  
  
obj.m();  
}  
}  

Output:A5@22b3ea59
       A5@22b3ea59


Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Why use inheritance in java
·        For Method Overriding (so runtime polymorphism can be achieved).
·        For Code Reusability.
Syntax of Java Inheritance
class Subclass-name extends Superclass-name  
{  
   //methods and fields  
}  
The extends keyword indicates that you are making a new class that derives from an existing class.
In the terminology of Java, a class that is inherited is called a super class. The new class is called a subclass.

Understanding the simple example of inheritance


Programmer is the subclass and Employee is the superclass. Relationship between two classes is Programmer IS-A Employee.It means that Programmer is a type of Employee.
class Employee{  
 float salary=40000;  
}  
class Programmer extends Employee{  
 int bonus=10000;  
 public static void main(String args[]){  
   Programmer p=new Programmer();  
   System.out.println("Programmer salary is:"+p.salary);  
   System.out.println("Bonus of Programmer is:"+p.bonus);  
}  
}  

 Programmer salary is:40000.0
 Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability.

Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.
 

Note: Multiple inheritance is not supported in java through class.
When a class extends multiple classes i.e. known as multiple inheritance. For Example:

Single Inheritance example program in Java
Class A
{
   public void methodA()
   {
     System.out.println("Base class method");
   }
}
 
Class B extends A
{
   public void methodB()
   {
     System.out.println("Child class method");
   }
   public static void main(String args[])
   {
     B obj = new B();
     obj.methodA(); //calling super class method
     obj.methodB(); //calling local method
  }
}

Multilevel inheritance.
class Car{
        public Car()
        {
               System.out.println("Class Car");
        }
        public void vehicleType()
        {
               System.out.println("Vehicle Type: Car");
        }
}
class Maruti extends Car{
        public Maruti()
        {
               System.out.println("Class Maruti");
        }
        public void brand()
        {
               System.out.println("Brand: Maruti");
        }
        public void speed()
        {
               System.out.println("Max: 90Kmph");
        }
}
public class Maruti800 extends Maruti{
 
         public Maruti800()
         {
                System.out.println("Maruti Model: 800");
         }
         public void speed()
               {
                       System.out.println("Max: 80Kmph");
               }
         public static void main(String args[])
         {
                Maruti800 obj=new Maruti800();
                obj.vehicleType();
                obj.brand();
                obj.speed();
         }
}
Output:
Class Car
Class Maruti
Maruti Model: 800
Vehicle Type: Car
Brand: Maruti
Max: 80Kmph

Hierarchical inheritance in the below example-
A.java
Class A
{
  public void methodA()
  {
     System.out.println("method of Class A");
  }
}
B.java
Class B extends A
{
  public void methodB()
  {
     System.out.println("method of Class B");
  }
}
C.java
Class C extends A
{
 public void methodC()
 {
 System.out.println("method of Class C");
 }
}
D.java
Class D extends A
{
  public void methodD()
  {
     System.out.println("method of Class D");
  }
}
MyClass.java
Class MyClass
{
  public void methodB()
  {
     System.out.println("method of Class B");
  }
  public static void main(String args[])
  {
     B obj1 = new B();
     C obj2 = new C();
     D obj3 = new D();
     obj1.methodA();
     obj2.methodA();
     obj3.methodA();
  }
}
The above would run perfectly fine with no errors and the output would be –
method of Class A
method of Class A
method of Class A

Q) Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now.
class A{  
void msg(){System.out.println("Hello");}  
}  
class B{  
void msg(){System.out.println("Welcome");}  
}  
class C extends A,B{//suppose if it were  
   
 Public Static void main(String args[]){  
   C obj=new C();  
   obj.msg();//Now which msg() method would be invoked?  
}  
}  

 Compile Time Error
Aggregation in Java
If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship.
Consider a situation, Employee object contains many informations such as id, name, emailId etc. It contains one more object named address, which contains its own informations such as city, state, country, zipcode etc. as given below.
class Employee{  
int id;  
String name;  
Address address;//Address is a class  
...  
}  
In such case, Employee has an entity reference address, so relationship is Employee HAS-A address.
Why use Aggregation?
·        For Code Reusability.

Simple Example of Aggregation

In this example, we have created the reference of Operation class in the Circle class.
class Operation{  
 int square(int n){  
  return n*n;  
 }  
}  
  
class Circle{  
 Operation op;//aggregation  
 double pi=3.14;  
    
 double area(int radius){  
   op=new Operation();  
   int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).  
   return pi*rsquare;  
 }  
 public static void main(String args[]){  
   Circle c=new Circle();  
   double result=c.area(5);  
   System.out.println(result);  
 }  
}  

Output:78.5


     
When use Aggregation?
·        Code reuse is also best achieved by aggregation when there is no is-a relationship.
·        Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of the objects involved; otherwise, aggregation is the best choice.

Understanding meaningful example of Aggregation
In this example, Employee has an object of Address, address object contains its own informations such as city, state, country etc. In such case relationship is Employee HAS-A address.
Address.java
public class Address {  
String city,state,country;  
  
public Address(String city, String state, String country) {  
    this.city = city;  
    this.state = state;  
    this.country = country;  
}  
  
}  
Emp.java
public class Emp {  
int id;  
String name;  
Address address;  
  
public Emp(int id, String name,Address address) {  
    this.id = id;  
    this.name = name;  
    this.address=address;  
}  
  
void display(){  
System.out.println(id+" "+name);  
System.out.println(address.city+" "+address.state+" "+address.country);  
}  
  
public static void main(String[] args) {  
Address address1=new Address("gzb","UP","india");  
Address address2=new Address("gno","UP","india");  
  
Emp e=new Emp(111,"varun",address1);  
Emp e2=new Emp(112,"arun",address2);  
      
e.display();  
e2.display();  
      
}  
}  

Output:111 varun
       gzb UP india
       112 arun
       gno UP india     


Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java.
In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
·        Method overriding is used to provide specific implementation of a method that is already provided by its super class.
·        Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
1.      method must have same name as in the parent class
2.      method must have same parameter as in the parent class.
3.      must be IS-A relationship (inheritance).


Understanding the problem without method overriding
Let's understand the problem that we may face in the program if we don't use method overriding.
class Vehicle{  
  void run(){System.out.println("Vehicle is running");}  
}  
class Bike extends Vehicle{  
    
  public static void main(String args[]){  
  Bike obj = new Bike();  
  obj.run();  
  }  
}  

Output:Vehicle is running
Problem is that I have to provide a specific implementation of run() method in subclass that is why we use method overriding.

Example of method overriding
In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method is same and there is IS-A relationship between the classes, so there is method overriding.
class Vehicle{  
void run(){System.out.println("Vehicle is running");}  
}  
class Bike2 extends Vehicle{  
void run(){System.out.println("Bike is running safely");}  
  
public static void main(String args[]){  
Bike2 obj = new Bike2();  
obj.run();  
}  

Output:Bike is running safely

Real example of Java Method Overriding
Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest.


class Bank{  
int getRateOfInterest(){return 0;}  
}  
  
class SBI extends Bank{  
int getRateOfInterest(){return 8;}  
}  
  
class ICICI extends Bank{  
int getRateOfInterest(){return 7;}  
}  
class AXIS extends Bank{  
int getRateOfInterest(){return 9;}  
}  
  
class Test2{  
public static void main(String args[]){  
SBI s=new SBI();  
ICICI i=new ICICI();  
AXIS a=new AXIS();  
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());  
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());  
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());  
}  
}  

Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Can we override static method?
No, static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it later.


Why we cannot override static method?
because static method is bound with class whereas instance method is bound with object. Static belongs to class area and instance belongs to heap area.

Can we override java main method?
No, because main is a static method.

Difference between method Overloading and Method Overriding in java
There are many differences between method overloading and method overriding in java. A list of differences between method overloading and method overriding are given below:
No.
Method Overloading
Method Overriding
1)
Method overloading is used to increase the readability of the program.
Method overriding is used to provide the specific implementation of the method that is already provided by its super class.
2)
Method overloading is performed within class.
Method overriding occurs in two classes that have IS-A (inheritance) relationship.
3)
In case of method overloading, parameter must be different.
In case of method overriding,parameter must be same.
4)
Method overloading is the example of compile time polymorphism.
Method overriding is the example of run time polymorphism.
5)
In java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter.
Return type must be same or covariant in method overriding.
Java Method Overloading example
class OverloadingExample{  
static int add(int a,int b){return a+b;}  
static int add(int a,int b,int c){return a+b+c;}  
}  
Java Method Overriding example
class Animal{  
void eat(){System.out.println("eating...");}  
}  
class Dog extends Animal{  
void eat(){System.out.println("eating bread...");}  
}  


Access Modifiers in java
There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class.
There are 4 types of java access modifiers:
1.      private
2.      default
3.      protected
4.      public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. Here, we will learn access modifiers.

1) private access modifier
The private access modifier is accessible only within class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data member and private method. We are accessing these private members from outside the class, so there is compile time error.
class A{  
private int data=40;  
private void msg(){System.out.println("Hello java");}  
}  
  
public class Simple{  
 public static void main(String args[]){  
   A obj=new A();  
   System.out.println(obj.data);//Compile Time Error  
   obj.msg();//Compile Time Error  
   }  
}  
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class from outside the class. For example:
class A{  
private A(){}//private constructor  
void msg(){System.out.println("Hello java");}  
}  
public class Simple{  
 public static void main(String args[]){  
   A obj=new A();//Compile Time Error  
 }  
}  
Note: A class cannot be private or protected except nested class.


2) default access modifier
If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only within package.
Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing the A class from outside its package, since A class is not public, so it cannot be accessed from outside the package.
//save by A.java  
package pack;  
class A{  
  void msg(){System.out.println("Hello");}  
}  
//save by B.java  
package mypack;  
import pack.*;  
class B{  
  public static void main(String args[]){  
   A obj = new A();//Compile Time Error  
   obj.msg();//Compile Time Error  
  }  
}  
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the package.

3) protected access modifier
The protected access modifier is accessible within package and outside the package but through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of pack package is public, so can be accessed from outside the package. But msg method of this package is declared as protected, so it can be accessed from outside the class only through inheritance.
//save by A.java  
package pack;  
public class A{  
protected void msg(){System.out.println("Hello");}  
}  
//save by B.java  
package mypack;  
import pack.*;  
  
class B extends A{  
  public static void main(String args[]){  
   B obj = new B();  
   obj.msg();  
  }  
}  
Output:Hello

4) public access modifier
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
Example of public access modifier
//save by A.java    
package pack;  
public class A{  
public void msg(){System.out.println("Hello");}  
}  
//save by B.java  
package mypack;  
import pack.*;  
  
class B{  
  public static void main(String args[]){  
   A obj = new A();  
   obj.msg();  
  }  
}  
Output:Hello

Understanding all java access modifiers
Let's understand the access modifiers by a simple table.
Access Modifier
within class
within package
outside package by subclass only
outside package
Private
Y
N
N
N
Default
Y
Y
N
N
Protected
Y
Y
Y
N
Public
Y
Y
Y
Y

Java access modifiers with method overriding
If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.
class A{  
protected void msg(){System.out.println("Hello java");}  
}  
  
public class Simple extends A{  
void msg(){System.out.println("Hello java");}//C.T.Error  
 public static void main(String args[]){  
   Simple obj=new Simple();  
   obj.msg();  
   }  
}  
The default modifier is more restrictive than protected. That is why there is compile time error.


ExceptionHandling with MethodOverriding in Java
There are many rules if we talk about methodoverriding with exception handling. The Rules are as follows:
·        If the superclass method does not declare an exception
Ø      If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception.
·        If the superclass method declares an exception
Ø      If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.
If the superclass method does not declare an exception
1) Rule: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception.
import java.io.*;  
class Parent{  
  void msg(){System.out.println("parent");}  
}  
  
class TestExceptionChild extends Parent{  
  void msg()throws IOException{  
    System.out.println("TestExceptionChild");  
  }  
  public static void main(String args[]){  
   Parent p=new TestExceptionChild();  
   p.msg();  
  }  
}  

Output:Compile Time Error


2) Rule: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but can declare unchecked exception.
import java.io.*;  
class Parent{  
  void msg(){System.out.println("parent");}  
}  
  
class TestExceptionChild1 extends Parent{  
  void msg()throws ArithmeticException{  
    System.out.println("child");  
  }  
  public static void main(String args[]){  
   Parent p=new TestExceptionChild1();  
   p.msg();  
  }  
}  
Output:child


If the superclass method declares an exception
1) Rule: If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.
Example in case subclass overridden method declares parent exception
import java.io.*;  
class Parent{  
  void msg()throws ArithmeticException{System.out.println("parent");}  
}  
  
class TestExceptionChild2 extends Parent{  
  void msg()throws Exception{System.out.println("child");}  
  
  public static void main(String args[]){  
   Parent p=new TestExceptionChild2();  
   try{  
   p.msg();  
   }catch(Exception e){}  
  }  
}  

Output:Compile Time Error

Example in case subclass overridden method declares same exception
import java.io.*;  
class Parent{  
  void msg()throws Exception{System.out.println("parent");}  
}  
  
class TestExceptionChild3 extends Parent{  
  void msg()throws Exception{System.out.println("child");}  
  
  public static void main(String args[]){  
   Parent p=new TestExceptionChild3();  
   try{  
   p.msg();  
   }catch(Exception e){}  
  }  
}  

Output:child

Example in case subclass overridden method declares subclass exception
import java.io.*;  
class Parent{  
  void msg()throws Exception{System.out.println("parent");}  
}  
  
class TestExceptionChild4 extends Parent{  
  void msg()throws ArithmeticException{System.out.println("child");}  
  
  public static void main(String args[]){  
   Parent p=new TestExceptionChild4();  
   try{  
   p.msg();  
   }catch(Exception e){}  
  }  
}  

Output:child

Example in case subclass overridden method declares no exception
import java.io.*;  
class Parent{  
  void msg()throws Exception{System.out.println("parent");}  
}  
  
class TestExceptionChild5 extends Parent{  
  void msg(){System.out.println("child");}  
  
  public static void main(String args[]){  
   Parent p=new TestExceptionChild5();  
   try{  
   p.msg();  
   }catch(Exception e){}  
  }  
}  

Output:child

Covariant Return Type
The covariant return type specifies that the return type may vary in the same direction as the subclass.
Before Java5, it was not possible to override any method by changing the return type. But now, since Java5, it is possible to override method by changing the return type if subclass overrides any method whose return type is Non-Primitive but it changes its return type to subclass type. Let's take a simple example:
Note: If you are beginner to java, skip this topic and return to it after OOPs concepts.


Simple example of Covariant Return Type
class A{  
A get(){return this;}  
}  
  
class B1 extends A{  
B1 get(){return this;}  
void message(){System.out.println("welcome to covariant return type");}  
  
public static void main(String args[]){  
new B1().get().message();  
}  
}  

Output:welcome to covariant return type
As you can see in the above example, the return type of the get() method of A class is A but the return type of the get() method of B class is B. Both methods have different return type but it is method overriding. This is known as covariant return type.

Super keyword in java
The super keyword in java is a reference variable that is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e. referred by super reference variable.
Usage of java super Keyword
1.      super is used to refer immediate parent class instance variable.
2.      super() is used to invoke immediate parent class constructor.
3.      super is used to invoke immediate parent class method.
1) super is used to refer immediate parent class instance variable.
Problem without super keyword
class Vehicle{  
  int speed=50;  
}  
class Bike3 extends Vehicle{  
  int speed=100;  
  void display(){  
   System.out.println(speed);//will print speed of Bike   
  }  
  public static void main(String args[]){  
   Bike3 b=new Bike3();  
   b.display();  
}  
}  

Output:100
In the above example Vehicle and Bike both class have a common property speed. Instance variable of current class is refered by instance bydefault, but I have to refer parent class instance variable that is why we use super keyword to distinguish between parent class instance variable and current class instance variable.

Solution by super keyword
//example of super keyword  
  
class Vehicle{  
  int speed=50;  
}  
  
class Bike4 extends Vehicle{  
  int speed=100;  
      
  void display(){  
   System.out.println(super.speed);//will print speed of Vehicle now  
  }  
  public static void main(String args[]){  
   Bike4 b=new Bike4();  
   b.display();  
     
}  
}  

Output:50
2) super is used to invoke parent class constructor.
The super keyword can also be used to invoke the parent class constructor as given below:
class Vehicle{  
  Vehicle(){System.out.println("Vehicle is created");}  
}  
  
class Bike5 extends Vehicle{  
  Bike5(){  
   super();//will invoke parent class constructor  
   System.out.println("Bike is created");  
  }  
  public static void main(String args[]){  
   Bike5 b=new Bike5();  
        
}  
}  

Output:Vehicle is created
       Bike is created
Note: super() is added in each class constructor automatically by compiler.



As we know well that default constructor is provided by compiler automatically but it also adds super() for the first statement.If you are creating your own constructor and you don't have either this() or super() as the first statement, compiler will provide super() as the first statement of the constructor.
Another example of super keyword where super() is provided by the compiler implicitly.
class Vehicle{  
  Vehicle(){System.out.println("Vehicle is created");}  
}  
  
class Bike6 extends Vehicle{  
  int speed;  
  Bike6(int speed){  
    this.speed=speed;  
    System.out.println(speed);  
  }  
  public static void main(String args[]){  
   Bike6 b=new Bike6(10);  
 }  
}  

Output:Vehicle is created
       10
3) super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It should be used in case subclass contains the same method as parent class as in the example given below:
class Person{  
void message(){System.out.println("welcome");}  
}  
  
class Student16 extends Person{  
void message(){System.out.println("welcome to java");}  
  
void display(){  
message();//will invoke current class message() method  
super.message();//will invoke parent class message() method  
}  
  
public static void main(String args[]){  
Student16 s=new Student16();  
s.display();  
}  
}  

Output:welcome to java
       welcome
In the above example Student and Person both classes have message() method if we call message() method from Student class, it will call the message() method of Student class not of Person class because priority is given to local.

In case there is no method in subclass as parent, there is no need to use super. In the example given below message() method is invoked from Student class but Student class does not have message() method, so you can directly call message() method.
Program in case super is not required
class Person{  
void message(){System.out.println("welcome");}  
}  
class Student17 extends Person{  
void display(){  
message();//will invoke parent class message() method  
}  
public static void main(String args[]){  
Student17 s=new Student17();  
s.display();  
}  
}  

Output:welcome

Instance initializer block:
Instance Initializer block is used to initialize the instance data member. It run each time when object of the class is created.
The initialization of the instance variable can be directly but there can be performed extra operations while initializing the instance variable in the instance initializer block.
Que) What is the use of instance initializer block while we can directly assign a value in instance data member? For example:
class Bike{  
    int speed=100;  
}  
Why use instance initializer block?
Suppose I have to perform some operations while assigning value to instance data member e.g. a for loop to fill a complex array or error handling etc.


Example of instance initializer block
Let's see the simple example of instance initializer block the performs initialization.
class Bike7{  
    int speed;  
      
    Bike7(){System.out.println("speed is "+speed);}  
   
    {speed=100;}  
       
    public static void main(String args[]){  
    Bike7 b1=new Bike7();  
    Bike7 b2=new Bike7();  
    }      
}  

Output:speed is 100
       speed is 100

There are three places in java where you can perform operations:
1.      method
2.      constructor
3.      block


What is invoked firstly instance initializer block or constructor?
class Bike8{  
    int speed;  
      
    Bike8(){System.out.println("constructor is invoked");}  
   
    {System.out.println("instance initializer block invoked");}  
       
    public static void main(String args[]){  
    Bike8 b1=new Bike8();  
    Bike8 b2=new Bike8();  
    }      
}  

Output:instance initializer block invoked
       constructor is invoked
       instance initializer block invoked
       constructor is invoked
In the above example, it seems that instance initializer block is firstly invoked but NO. Instance intializer block is invoked at the time of object creation. The java compiler copies the instance initializer block in the constructor after the first statement super(). So firstly, constructor is invoked. Let's understand it by the figure given below:
Note: The java compiler copies the code of instance initializer block in every constructor.


Rules for instance initializer block :
There are mainly three rules for the instance initializer block. They are as follows:
1.      The instance initializer block is created when instance of the class is created.
2.      The instance initializer block is invoked after the parent class constructor is invoked (i.e. after super() constructor call).
3.      The instance initializer block comes in the order in which they appear.
Program of instance initializer block that is invoked after super()
class A{  
A(){  
System.out.println("parent class constructor invoked");  
}  
}  
class B2 extends A{  
B2(){  
super();  
System.out.println("child class constructor invoked");  
}  
  
{System.out.println("instance initializer block is invoked");}  
  
public static void main(String args[]){  
B2 b=new B2();  
}  
}  

Output:parent class constructor invoked
       instance initializer block is invoked
       child class constructor invoked


Another example of instance block
class A{  
A(){  
System.out.println("parent class constructor invoked");  
}  
}  
  
class B3 extends A{  
B3(){  
super();  
System.out.println("child class constructor invoked");  
}  
  
B3(int a){  
super();  
System.out.println("child class constructor invoked "+a);  
}  
  
{System.out.println("instance initializer block is invoked");}  
  
public static void main(String args[]){  
B3 b1=new B3();  
B3 b2=new B3(10);  
}  
}  

Output:parent class constructor invoked
       instance initializer block is invoked
       child class constructor invoked
       parent class constructor invoked
       instance initializer block is invoked
       child class constructor invoked 10
Next Topic

Final Keyword In Java
The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:
1.      variable
2.      method
3.      class
The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only. We will have detailed learning of these. Let's first learn the basics of final keyword.


1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
Example of final variable
There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because final variable once assigned a value can never be changed.
class Bike9{  
 final int speedlimit=90;//final variable  
 void run(){  
  speedlimit=400;  
 }  
 public static void main(String args[]){  
 Bike9 obj=new  Bike9();  
 obj.run();  
 }  
}//end of class  

Output:Compile Time Error


2) Java final method
If you make any method as final, you cannot override it.
Example of final method
class Bike{  
  final void run(){System.out.println("running");}  
}  
     
class Honda extends Bike{  
   void run(){System.out.println("running safely with 100kmph");}  
     
   public static void main(String args[]){  
   Honda honda= new Honda();  
   honda.run();  
   }  
}  

Output:Compile Time Error

3) Java final class
If you make any class as final, you cannot extend it.
Example of final class
final class Bike{}  
class Honda1 extends Bike{  
  void run(){System.out.println("running safely with 100kmph");}  
  public static void main(String args[]){  
  Honda1 honda= new Honda();  
  honda.run();  
  }  
}  

Output:Compile Time Error

Q) Is final method inherited?
Ans) Yes, final method is inherited but you cannot override it. For Example:
class Bike{  
  final void run(){System.out.println("running...");}  
}  
class Honda2 extends Bike{  
   public static void main(String args[]){  
    new Honda2().run();  
   }  
}  

Output:running...

Q) What is blank or uninitialized final variable?
A final variable that is not initialized at the time of declaration is known as blank final variable.
If you want to create a variable that is initialized at the time of creating object and once initialized may not be changed, it is useful. For example PAN CARD number of an employee.
It can be initialized only in constructor.
Example of blank final variable
class Student{  
int id;  
String name;  
final String PAN_CARD_NUMBER;  
...  
}  
Que) Can we initialize blank final variable?
Yes, but only in constructor. For example:
class Bike10{  
  final int speedlimit;//blank final variable  
    
  Bike10(){  
  speedlimit=70;  
  System.out.println(speedlimit);  
  }  
  
  public static void main(String args[]){  
    new Bike10();  
 }  
}  

Output:70

static blank final variable
A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block.
Example of static blank final variable
class A{  
  static final int data;//static blank final variable  
  static{ data=50;}  
  public static void main(String args[]){  
    System.out.println(A.data);  
 }  
}  

Q) What is final parameter?
If you declare any parameter as final, you cannot change the value of it.
class Bike11{  
  int cube(final int n){  
   n=n+2;//can't be changed as n is final  
   n*n*n;  
  }  
  public static void main(String args[]){  
    Bike11 b=new Bike11();  
    b.cube(5);  
 }  
}  

Output:Compile Time Error

Q) Can we declare a constructor final?
No, because constructor is never inherited.
Next Topic

Polymorphism in Java
Polymorphism in java is a concept by which we can perform a single action by different ways. Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.
If you overload static method in java, it is the example of compile time polymorphism. Here, we will focus on runtime polymorphism in java.
Runtime Polymorphism in Java
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.
Let's first understand the upcasting before Runtime Polymorphism.
Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example:


class A{}  
class B extends A{}  
A a=new B();//upcasting  


Example of Java Runtime Polymorphism
In this example, we are creating two classes Bike and Splendar. Splendar class extends Bike class and overrides its run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, subclass method is invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
class Bike{  
  void run(){System.out.println("running");}  
}  
class Splender extends Bike{  
  void run(){System.out.println("running safely with 60km");}  
  
  public static void main(String args[]){  
    Bike b = new Splender();//upcasting  
    b.run();  
  }  
}  

Output:running safely with 60km.
Real example of Java Runtime Polymorphism
Consider a scenario, Bank is a class that provides method to get the rate of interest. But, rate of interest may differ according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest.

Note: It is also given in method overriding but there was no upcasting.
class Bank{  
int getRateOfInterest(){return 0;}  
}  
  
class SBI extends Bank{  
int getRateOfInterest(){return 8;}  
}  
  
class ICICI extends Bank{  
int getRateOfInterest(){return 7;}  
}  
class AXIS extends Bank{  
int getRateOfInterest(){return 9;}  
}  
  
class Test3{  
public static void main(String args[]){  
Bank b1=new SBI();  
Bank b2=new ICICI();  
Bank b3=new AXIS();  
System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());  
System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());  
System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());  
}  
}  

Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Java Runtime Polymorphism with data member
Method is overridden not the datamembers, so runtime polymorphism can't be achieved by data members.
In the example given below, both the classes have a datamember speedlimit, we are accessing the datamember by the reference variable of Parent class which refers to the subclass object. Since we are accessing the datamember which is not overridden, hence it will access the datamember of Parent class always.
Rule: Runtime polymorphism can't be achieved by data members.
class Bike{  
 int speedlimit=90;  
}  
class Honda3 extends Bike{  
 int speedlimit=150;  
  
 public static void main(String args[]){  
  Bike obj=new Honda3();  
  System.out.println(obj.speedlimit);//90  
}  

Output:90
Java Runtime Polymorphism with Multilevel Inheritance
Let's see the simple example of Runtime Polymorphism with multilevel inheritance.
class Animal{  
void eat(){System.out.println("eating");}  
}  
class Dog extends Animal{  
void eat(){System.out.println("eating fruits");}  
}  
class BabyDog extends Dog{  
void eat(){System.out.println("drinking milk");}  
public static void main(String args[]){  
Animal a1,a2,a3;  
a1=new Animal();  
a2=new Dog();  
a3=new BabyDog();   
a1.eat();  
a2.eat();  
a3.eat();  
}  
}  

Output: eating
        eating fruits
        drinking Milk

Try for Output
class Animal{  
void eat(){System.out.println("animal is eating...");}  
}    
class Dog extends Animal{  
void eat(){System.out.println("dog is eating...");}  
}  
class BabyDog1 extends Dog{  
public static void main(String args[]){  
Animal a=new BabyDog1();  
a.eat();  
}}  

Output: Dog is eating
Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is invoked.
 
Static Binding and Dynamic Binding

Connecting a method call to the method body is known as binding.
There are two types of binding
1.      static binding (also known as early binding).
2.      dynamic binding (also known as late binding).
Understanding Type
Let's understand the type of instance.
1) variables have a type
Each variable has a type, it may be primitive and non-primitive.
int data=30;  
Here data variable is a type of int.
2) References have a type
class Dog{  
 public static void main(String args[]){  
  Dog d1;//Here d1 is a type of Dog  
 }  
}  
3) Objects have a type
An object is an instance of particular java class,but it is also an instance of its superclass.
class Animal{}  
class Dog extends Animal{  
 public static void main(String args[]){  
  Dog d1=new Dog();  
 }  
}  
Here d1 is an instance of Dog class, but it is also an instance of Animal.


static binding
When type of the object is determined at compiled time(by the compiler), it is known as static binding.
If there is any private, final or static method in a class, there is static binding.
Example of static binding
class Dog{  
 private void eat(){System.out.println("dog is eating...");}  
  
 public static void main(String args[]){  
  Dog d1=new Dog();  
  d1.eat();  
 }  
}  


Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
Example of dynamic binding
class Animal{  
 void eat(){System.out.println("animal is eating...");}  
}  
  
class Dog extends Animal{  
 void eat(){System.out.println("dog is eating...");}  
  
 public static void main(String args[]){  
  Animal a=new Dog();  
  a.eat();  
 }  
}  

Output:dog is eating...
In the above example object type cannot be determined by the compiler, because the instance of Dog is also an instance of Animal.So compiler doesn't know its type, only its base type.
Next Topic

Java instanceof
The java instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface).
The instanceof in java is also known as typecomparison operator because it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that has null value, it returns false.
Simple example of java instanceof
Let's see the simple example of instance operator where it tests the current class.
class Simple1{  
 public static void main(String args[]){  
 Simple1 s=new Simple1();  
 System.out.println(s instanceof Simple1);//true  
 }  
}  

Output:true


An object of subclass type is also a type of parent class. For example, if Dog extends Animal then object of Dog can be referred by either Dog or Animal class.
Another example of java instanceof operator
class Animal{}  
class Dog1 extends Animal{//Dog inherits Animal  
  
 public static void main(String args[]){  
 Dog1 d=new Dog1();  
 System.out.println(d instanceof Animal);//true  
 }  
}  

Output:true

instanceof in java with a variable that have null value
If we apply instanceof operator with a variable that have null value, it returns false. Let's see the example given below where we apply instanceof operator with the variable that have null value.
class Dog2{  
 public static void main(String args[]){  
  Dog2 d=null;  
  System.out.println(d instanceof Dog2);//false  
 }  
}  

Output:false

Downcasting with java instanceof operator
When Subclass type refers to the object of Parent class, it is known as downcasting. If we perform it directly, compiler gives Compilation error. If you perform it by typecasting, ClassCastException is thrown at runtime. But if we use instanceof operator, downcasting is possible.
Ø      Dog d=new Animal();//Compilation error  
If we perform downcasting by typecasting, ClassCastException is thrown at runtime.
Ø      Dog d=(Dog)new Animal();  
//Compiles successfully but ClassCastException is thrown at runtime  
Possibility of downcasting with instanceof
Let's see the example, where downcasting is possible by instanceof operator.
class Animal { }  
  
class Dog3 extends Animal {  
  static void method(Animal a) {  
    if(a instanceof Dog3){  
       Dog3 d=(Dog3)a;//downcasting  
       System.out.println("ok downcasting performed");  
    }  
  }  
   
  public static void main (String [] args) {  
    Animal a=new Dog3();  
    Dog3.method(a);  
  }  
    
 }  

Output:ok downcasting performed

Downcasting without the use of java instanceof
Downcasting can also be performed without the use of instanceof operator as displayed in the following example:
class Animal { }  
class Dog4 extends Animal {  
  static void method(Animal a) {  
       Dog4 d=(Dog4)a;//downcasting  
       System.out.println("ok downcasting performed");  
  }  
   public static void main (String [] args) {  
    Animal a=new Dog4();  
    Dog4.method(a);  
  }  
}  

Output:ok downcasting performed
Let's take closer look at this, actual object that is referred by a, is an object of Dog class. So if we downcast it, it is fine. But what will happen if we write:
Animal a=new Animal();  
Dog.method(a);  
//Now ClassCastException but not in case of instanceof operator  
Understanding Real use of instanceof in java
Let's see the real use of instanceof keyword by the example given below.
interface Printable{}  
class A implements Printable{  
public void a(){System.out.println("a method");}  
}  
class B implements Printable{  
public void b(){System.out.println("b method");}  
}  
  
class Call{  
void invoke(Printable p){//upcasting  
if(p instanceof A){  
A a=(A)p;//Downcasting   
a.a();  
}  
if(p instanceof B){  
B b=(B)p;//Downcasting   
b.b();  
}  
  
}  
}//end of Call class  
  
class Test4{  
public static void main(String args[]){  
Printable p=new B();  
Call c=new Call();  
c.invoke(p);  
}  
}  

Output: b method
Next Topic

Abstract class in Java
A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-abstract methods (method with body).
Ø      Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Ø      Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don't know the internal processing about the message delivery.
Ø      Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstaction
There are two ways to achieve abstraction in java
Ø      Abstract class (0 to 100%)
Ø      Interface (100%)

Abstract class in Java
A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.
Example abstract class
abstract class A{}  

abstract method
A method that is declared as abstract and does not have implementation is known as abstract method.
Example abstract method
abstract void printStatus();//no body and abstract  

Example of abstract class that has abstract method
In this example, Bike the abstract class that contains only one abstract method run. It implementation is provided by the Honda class.
abstract class Bike{  
  abstract void run();  
}  
  
class Honda4 extends Bike{  
void run(){System.out.println("running safely..");}  
  
public static void main(String args[]){  
 Bike obj = new Honda4();  
 obj.run();  
}  
}  

running safely..

Understanding the real scenario of abstract class
In this example, Shape is the abstract class, its implementation is provided by the Rectangle and Circle classes. Mostly, we don't know about the implementation class (i.e. hidden to the end user) and object of the implementation class is provided by the factory method.
A factory method is the method that returns the instance of the class. We will learn about the factory method later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be invoked.
File: TestAbstraction1.java
abstract class Shape{  
abstract void draw();  
}  
//In real scenario, implementation is provided by others i.e. unknown by end user  
class Rectangle extends Shape{  
void draw(){System.out.println("drawing rectangle");}  
}  
  
class Circle1 extends Shape{  
void draw(){System.out.println("drawing circle");}  
}  
  
//In real scenario, method is called by programmer or user  
class TestAbstraction1{  
public static void main(String args[]){  
Shape s=new Circle1();//In real scenario, object is provided through method e.g. getShape() method  
s.draw();  
}  
}  

drawing circle


Another example of abstract class in java
File: TestBank.java
 abstract class Bank{    
abstract int getRateOfInterest();    
}    
    
class SBI extends Bank{    
int getRateOfInterest(){return 7;}    
}    
class PNB extends Bank{    
int getRateOfInterest(){return 7;}    
}    
    
class TestBank{    
public static void main(String args[]){    
Bank b=new SBI();//if object is PNB, method of PNB will be invoked    
int interest=b.getRateOfInterest();    
System.out.println("Rate of Interest is: "+interest+" %");    
}}    

Rate of Interest is: 7 %


Abstract class having constructor, data member, methods etc.
An abstract class can have data member, abstract method, method body, constructor and even main() method.
File: TestAbstraction2.java
//example of abstract class that have method body  
 abstract class Bike{  
   Bike(){System.out.println("bike is created");}  
   abstract void run();  
   void changeGear(){System.out.println("gear changed");}  
 }  
  
 class Honda extends Bike{  
 void run(){System.out.println("running safely..");}  
 }  
 class TestAbstraction2{  
 public static void main(String args[]){  
  Bike obj = new Honda();  
  obj.run();  
  obj.changeGear();  
 }  
}  

       bike is created
       running safely..
       gear changed

Rule: If there is any abstract method in a class, that class must be abstract.
class Bike12{  
abstract void run();  
}  

compile time error
Rule: If you are extending any abstract class that have abstract method, you must either provide the implementation of the method or make this class abstract.


Another real scenario of abstract class
The abstract class can also be used to provide some implementation of the interface. In such case, the end user may not be forced to override all the methods of the interface.
Note: If you are beginner to java, learn interface first and skip this example.
interface A{  
void a();  
void b();  
void c();  
void d();  
}  
abstract class B implements A{  
public void c(){System.out.println("I am C");}  
}  
class M extends B{  
public void a(){System.out.println("I am a");}  
public void b(){System.out.println("I am b");}  
public void d(){System.out.println("I am d");}  
}   
class Test5{  
public static void main(String args[]){  
A a=new M();  
a.a();  
a.b();  
a.c();  
a.d();  
}}  

Output:I am a
       I am b
       I am c
       I am d
Next Topi

Interface in Java
Ø      An interface in java is a blueprint of a class. It has static constants and abstract methods only.
Ø      The interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve fully abstraction and multiple inheritance in Java.
Ø      Java Interface also represents IS-A relationship.
Ø      It cannot be instantiated just like abstract class.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
1.      It is used to achieve fully abstraction.
2.      By interface, we can support the functionality of multiple inheritance.
3.      It can be used to achieve loose coupling.
The java compiler adds public and abstract keywords before the interface method and public, static and final keywords before data members.
In other words, Interface fields are public, static and final bydefault, and methods are public and abstract.


Understanding relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another interface but a class implements an interface.

Simple example of Java interface
In this example, Printable interface have only one method, its implementation is provided in the A class.
interface printable{  
void print();  
}  
  
class A6 implements printable{  
public void print(){System.out.println("Hello");}  
  
public static void main(String args[]){  
A6 obj = new A6();  
obj.print();  
 }  
}  

Output:Hello


Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple inheritance.



interface Printable{  
void print();  
}  
  
interface Showable{  
void show();  
}  
  
class A7 implements Printable,Showable{  
  
public void print(){System.out.println("Hello");}  
public void show(){System.out.println("Welcome");}  
  
public static void main(String args[]){  
A7 obj = new A7();  
obj.print();  
obj.show();  
 }  
}  
Output:Hello
       Welcome

Q) Multiple inheritance is not supported through class in java but it is possible by interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in case of class. But it is supported in case of interface because there is no ambiguity as implementation is provided by the implementation class. For example:
interface Printable{  
void print();  
}  
interface Showable{  
void print();  
}  
  
class TestTnterface1 implements Printable,Showable{  
public void print(){System.out.println("Hello");}  
public static void main(String args[]){  
TestTnterface1 obj = new TestTnterface1();  
obj.print();  
 }  
}  
Hello
As you can see in the above example, Printable and Showable interface have same methods but its implementation is provided by class TestTnterface1, so there is no ambiguity.

Interface inheritance
A class implements interface but one interface extends another interface .
interface Printable{  
void print();  
}  
interface Showable extends Printable{  
void show();  
}  
class Testinterface2 implements Showable{  
  
public void print(){System.out.println("Hello");}  
public void show(){System.out.println("Welcome");}  
  
public static void main(String args[]){  
Testinterface2 obj = new Testinterface2();  
obj.print();  
obj.show();  
 }  
}  
       Hello
       Welcome

Q) What is marker or tagged interface?
An interface that have no member is known as marker or tagged interface. For example: Serializable, Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation.
//How Serializable interface is written?  
public interface Serializable{  
}  


Nested Interface in Java
Note: An interface can have another interface i.e. known as nested interface. For example:
interface printable{  
 void print();  
 interface MessagePrintable{  
   void msg();  
 }  
}  
Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
Abstract class
Interface
1) Abstract class can have abstract and non-abstract methods.
Interface can have only abstract methods.
2) Abstract class doesn't support multiple inheritance.
Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static and non-static variables.
Interface has only static and final variables.
4) Abstract class can have static methods, main method and constructor.
Interface can't have static methods, main method or constructor.
5) Abstract class can provide the implementation of interface.
Interface can't provide the implementation of abstract class.
6) The abstract keyword is used to declare abstract class.
The interface keyword is used to declare interface.
7) Example:
public abstract class Shape{
public abstract void draw();
}
Example:
public interface Drawable{
void draw();
}
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction (100%).
Example of abstract class and interface in Java
Let's see a simple example where we are using interface and abstract class both.
//Creating interface that has 4 methods  
interface A{  
void a();//bydefault, public and abstract  
void b();  
void c();  
void d();  
}  
  
//Creating abstract class that provides the implementation of one method of A interface  
abstract class B implements A{  
public void c(){System.out.println("I am C");}  
}  
  
//Creating subclass of abstract class, now we need to provide the implementation of rest of the methods  
class M extends B{  
public void a(){System.out.println("I am a");}  
public void b(){System.out.println("I am b");}  
public void d(){System.out.println("I am d");}  
}  
  
//Creating a test class that calls the methods of A interface  
class Test5{  
public static void main(String args[]){  
A a=new M();  
a.a();  
a.b();  
a.c();  
a.d();  
}}  
Output:
       I am a
       I am b
       I am c
       I am d
Next Topic

Java Package
Ø      A java package is a group of similar types of classes, interfaces and sub-packages.
Ø      Package in java can be categorized in two form, built-in package and user-defined package.
Ø      There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Ø      Here, we will have the detailed learning of creating and using user-defined packages.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.


Simple example of java package
The package keyword is used to create a package in java.
//save as Simple.java  
package mypack;  
public class Simple{  
 public static void main(String args[]){  
    System.out.println("Welcome to package");  
   }  
}  
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
javac -d directory javafilename  
For example
javac -d . Simple.java  
The -d switch specifies the destination where to put the generated class file. You can use any directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package within the same directory, you can use . (dot).

How to run java package program
You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents the current folder.


How to access package from another package?
There are three ways to access the package from outside the package.
1.      import package.*;
2.      import package.classname;
3.      fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current package.
Example of package that import the packagename.*
//save by A.java  
package pack;  
public class A{  
  public void msg(){System.out.println("Hello");}  
}  
//save by B.java  
package mypack;  
import pack.*;  
  
class B{  
  public static void main(String args[]){  
   A obj = new A();  
   obj.msg();  
  }  
}  
Output:Hello


2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
//save by A.java  
  
package pack;  
public class A{  
  public void msg(){System.out.println("Hello");}  
}  
//save by B.java  
package mypack;  
import pack.A;  
  
class B{  
  public static void main(String args[]){  
   A obj = new A();  
   obj.msg();  
  }  
}  
Output:Hello

3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class.
Example of package by import fully qualified name
//save by A.java  
package pack;  
public class A{  
  public void msg(){System.out.println("Hello");}  
}  
//save by B.java  
package mypack;  
class B{  
  public static void main(String args[]){  
   pack.A obj = new pack.A();//using fully qualified name  
   obj.msg();  
  }  
}  
Output:Hello
Note: If you import a package, subpackages will not be imported.
If you import a package, all the classes and interface of that package will be imported excluding the classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.

Note: Sequence of the program must be package then import then class.


Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the package further.
Let's take an example, Sun Microsystem has definded a package named java that contains many classes like System, String, Reader, Writer, Socket etc. These classes represent a particular group e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java package into subpackages such as lang, net, io etc. and put the Input/Output related classes in io package, Server and ServerSocket classes in net packages and so on.
The standard of defining package is domain.company.package e.g. com.javatpoint.bean or org.sssit.dao.
Example of Subpackage
package com.javatpoint.core;  
class Simple{  
  public static void main(String args[]){  
   System.out.println("Hello subpackage");  
  }  
}  
To Compile: javac -d . Simple.java
To Run: java com.javatpoint.core.Simple
Output:Hello subpackage

How to send the class file to another directory or drive?
There is a scenario, I want to put the class file of A.java source file in classes folder of c: drive. For example:


//save as Simple.java  
package mypack;  
public class Simple{  
 public static void main(String args[]){  
    System.out.println("Welcome to package");  
   }  
}  
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set classpath of the directory where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Another way to run this program by -classpath switch of java:
The -classpath switch can be used with javac and java tool.
To run this program from e:\source directory, you can use -classpath switch of java that tells where to look for class file. For example:
e:\sources> java -classpath c:\classes mypack.Simple
Output:Welcome to package


Ways to load the class files or jar files
There are two ways to load the class files temporary and permanent.
Temporary
Ø      By setting the classpath in the command prompt
Ø      By -classpath switch
Permanent
Ø      By setting the classpath in the environment variables
Ø      By creating the jar file, that contains all the class files, and copying the jar file in the jre/lib/ext folder.

Rule: There can be only one public class in a java source file and it must be saved by the public class name.
//save as C.java otherwise Compilte Time Error  
  
class A{}  
class B{}  
public class C{}  


How to put two public classes in a package?
If you want to put two public classes in a package, have two java source files containing one public class, but keep the package name same. For example:
//save as A.java  
package javatpoint;  
public class A{}  
//save as B.java  
package javatpoint;  
public class B{}  


What is static import feature of Java5?
Static Import:
The static import feature of Java 5 facilitate the java programmer to access any static member of a class directly. There is no need to qualify it by the class name.
Advantage of static import:
Less coding is required if you have access any static member of a class oftenly.
Disadvantage of static import:
If you overuse the static import feature, it makes the program unreadable and unmaintainable.

Simple Example of static import
import static java.lang.System.*;    
class StaticImportExample{  
  public static void main(String args[]){  
     
   out.println("Hello");//Now no need of System.out  
   out.println("Java");  
  
 }   
}  
      
Output:Hello
       Java
 
What is the difference between import and static import?
The import allows the java programmer to access classes of a package without package qualification whereas the static import feature allows to access the static members of a class without the class qualification. The import provides accessibility to classes and interface whereas static import provides accessibility to static members of the class.
What about package class?
Package class
The package class provides methods to get information about the specification and implementation of a package. It provides methods such as getName(), getImplementationTitle(), getImplementationVendor(), getImplementationVersion() etc.
Example of Package class
In this example, we are printing the details of java.lang package by invoking the methods of package class.
class PackageInfo{  
public static void main(String args[]){  
Package p=Package.getPackage("java.lang");  
System.out.println("package name: "+p.getName());  
System.out.println("Specification Title: "+p.getSpecificationTitle());  
System.out.println("Specification Vendor: "+p.getSpecificationVendor());  
System.out.println("Specification Version: "+p.getSpecificationVersion());  
System.out.println("Implementaion Title: "+p.getImplementationTitle());  
System.out.println("Implementation Vendor: "+p.getImplementationVendor());  
System.out.println("Implementation Version: "+p.getImplementationVersion());  
System.out.println("Is sealed: "+p.isSealed());    
 }  
}  
Output:package name: java.lang
       Specification Title: Java Plateform API Specification
       Specification Vendor: Sun Microsystems, Inc.
       Specification Version: 1.6
       Implemenation Title: Java Runtime Environment
       Implemenation Vendor: Sun Microsystems, Inc.
       Implemenation Version: 1.6.0_30
       IS sealed: false


Encapsulation in Java
Encapsulation in java is a process of wrapping code and data together into a single unit, for example capsule i.e. mixed of several medicines.


We can create a fully encapsulated class in java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it.
The Java Bean class is the example of fully encapsulated class.
Advantage of Encapsulation in java
 By providing only setter or getter method, you can make the class read-only or write-only.
It provides you the control over the data. Suppose you want to set the value of id i.e. greater than 100 only, you can write the logic inside the setter method.
Simple example of encapsulation in java
Let's see the simple example of encapsulation that has only one field with its setter and getter methods.
//save as Student.java  
public class Student{  
private String name;  
   
public String getName(){  
return name;  
}  
public void setName(String name){  
this.name=name  
}  
}  
//save as Test.java  
class Test{  
public static void main(String[] args){  
Student s=new Student();  
s.setName("vijay");  
System.out.println(s.getName());  
}  
}  
Compile By: javac -d . Test.java
Run By: java com.javatpoint.Test
Output: vijay

Object class in Java
Ø      The Object class is the parent class of all the classes in java bydefault. In other words, it is the topmost class of java.
Ø      The Object class is beneficial if you want to refer any object whose type you don't know. Notice that parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any type like Employee,Student etc, we can use Object class reference to refer that object. For example:
Object obj=getObject();//we don't what object would be returned from this method  
The Object class provides some common behaviours to all the objects such as object can be compared, object can be cloned, object can be notified etc.


Methods of Object class
The Object class provides many methods. They are as follows:

Method
Description
public final ClassgetClass()
returns the Class class object of this object. The Class class can further be used to get the metadata of this class.
public int hashCode()
returns the hashcode number for this object.
public boolean equals(Object obj)
compares the given object to this object.
protected Object clone() throws CloneNotSupportedException
creates and returns the exact copy (clone) of this object.
public String toString()
returns the string representation of this object.
public final void notify()
wakes up single thread, waiting on this object's monitor.
public final void notifyAll()
wakes up all the threads, waiting on this object's monitor.
public final void wait(long timeout)throws InterruptedException
causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method).
public final void wait(long timeout,int nanos)throws InterruptedException
causes the current thread to wait for the specified miliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method).
public final void wait()throws InterruptedException
causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method).
protected void finalize()throws Throwable
is invoked by the garbage collector before object is being garbage collected.
Object Cloning in Java



The object cloning is a way to create exact copy of an object. For this purpose, clone() method of Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generatesCloneNotSupportedException.
The clone() method is defined in the Object class. Syntax of the clone() method is as follows:
protected Object clone() throws CloneNotSupportedException  
Why use clone() method ?
The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new keyword, it will take a lot of processing to be performed that is why we use object cloning.
Advantage of Object cloning
Less processing task.
Example of clone() method (Object cloning)
Let's see the simple example of object cloning
class Student18 implements Cloneable{  
int rollno;  
String name;  
  
Student18(int rollno,String name){  
this.rollno=rollno;  
this.name=name;  
}  
  
public Object clone()throws CloneNotSupportedException{  
return super.clone();  
}  
  
public static void main(String args[]){  
try{  
Student18 s1=new Student18(101,"amit");  
  
Student18 s2=(Student18)s1.clone();  
  
System.out.println(s1.rollno+" "+s1.name);  
System.out.println(s2.rollno+" "+s2.name);  
  
}catch(CloneNotSupportedException c){}  
  
}  
}  
Output:101 amit
       101 amit
example of object cloning
class Student implements Cloneable{
int rollno;
String name;

Student(int rollno,String name){
this.rollno=rollno;
this.name=name;
}

public Object clone()throws CloneNotSupportedException{
return super.clone();
}

public static void main(String args[]){
try{
Student s1=new Student(101,"amit");

Student s2=(Student)s1.clone();

System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);

}catch(CloneNotSupportedException c){}

}
}
As you can see in the above example, both reference variables have the same value. Thus, the clone() copies the values of an object to another. So we don't need to write explicit code to copy the value of an object to another.
If we create another object by new keyword and assign the values of another object to this one, it will require a lot of processing on this object. So to save the extra processing task we use clone() method.

Wrapper class in Java
Ø      Wrapper class in java provides the mechanism to convert primitive into object and object into primitive.
Ø      Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object into primitive automatically. The automatic conversion of primitive into object is known and autoboxing and vice-versa unboxing.
One of the eight classes of java.lang package are known as wrapper class in java. The list of eight wrapper classes are given below:
Primitive Type
Wrapper class
boolean
Boolean
char
Character
byte
Byte
short
Short
int
Integer
long
Long
float
Float
double
Double
Wrapper class Example: Primitive to Wrapper
public class WrapperExample1{  
public static void main(String args[]){  
//Converting int into Integer  
int a=20;  
Integer i=Integer.valueOf(a);//converting int into Integer  
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally  
  
System.out.println(a+" "+i+" "+j);  
}}  
Output:
20 20 20
Wrapper class Example: Wrapper to Primitive
public class WrapperExample2{    
public static void main(String args[]){    
//Converting Integer to int    
Integer a=new Integer(3);    
int i=a.intValue();//converting Integer to int  
int j=a;//unboxing, now compiler will write a.intValue() internally    
    
System.out.println(a+" "+i+" "+j);    
}}    
Output:
3 3 3

Java Strictfp Keyword
Java strictfp keyword ensures that you will get the same result on every platform if you perform operations in the floating-point variable. The precision may differ from platform to platform that is why java programming language have provided the strictfp keyword, so that you get same result on every platform. So, now you have better control over the floating-point arithmetic.

Legal code for strictfp keyword
The strictfp keyword can be applied on methods, classes and interfaces.
strictfp class A{}//strictfp applied on class  
strictfp interface M{}//strictfp applied on interface  
class A{  
strictfp void m(){}//strictfp applied on method  
}  


Illegal code for strictfp keyword
The strictfp keyword cannot be applied on abstract methods, variables or constructors.
class B{  
strictfp abstract void m();//Illegal combination of modifiers  
}  
class B{  
strictfp int data=10;//modifier strictfp not allowed here  
}  
class B{  
strictfp B(){}//modifier strictfp not allowed here  
}  
Next Topi

Creating API Document | javadoc tool
We can create document api in java by the help of javadoc tool. In the java file, we must use the documentation comment /**... */ to post information for the class, method, constructor, fields etc.
Let's see the simple class that contains documentation comment.
package com.abc;  
/** This class is a user-defined class that contains one methods cube.*/  
public class M{  
  
/** The cube method prints cube of the given number */  
public static void  cube(int n){System.out.println(n*n*n);}  
}  
To create the document API, you need to use the javadoc tool followed by java file name. There is no need to compile the javafile.
On the command prompt, you need to write:
javadoc M.java
to generate the document api. Now, there will be created a lot of html files. Open the index.html file to get the information about the classes.

Java Command Line Arguments
1.      Command Line Argument
2.      Simple example of command-line argument
3.      Example of command-line argument that prints all the values
The java command-line argument is an argument i.e. passed at the time of running the java program.
The arguments passed from the console can be received in the java program and it can be used as an input.
So, it provides a convenient way to check the behavior of the program for the different values. You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
Simple example of command-line argument in java
In this example, we are receiving only one argument and printing it. To run this java program, you must pass at least one argument from the command prompt.
class CommandLineExample{  
public static void main(String args[]){  
System.out.println("Your first argument is: "+args[0]);  
}  
}  
compile by > javac CommandLineExample.java  
run by > java CommandLineExample sonoo  
Output: Your first argument is: sonoo


Example of command-line argument that prints all the values
In this example, we are printing all the arguments passed from the command-line. For this purpose, we have traversed the array using for loop.
class A{  
public static void main(String args[]){  
  
for(int i=0;i<args.length;i++)  
System.out.println(args[i]);  
  
}  
}  
compile by > javac A.java  
run by > java A sonoo jaiswal 1 3 abc  
Output: sonoo
       jaiswal
       1
       3
       abc
     
Difference between object and class
There are many differences between object and class. A list of differences between object and class are given below:
No.
Object
Class
1)
Object is an instance of a class.
Class is a blueprint or template from which objects are created.
2)
Object is a real world entity such as pen, laptop, mobile, bed, keyboard, mouse, chair etc.
Class is a group of similar objects.
3)
Object is a physical entity.
Class is a logical entity.
4)
Object is created through new keyword mainly e.g.
Student s1=new Student();
Class is declared usingclass keyword e.g.
class Student{}
5)
Object is created many times as per requirement.
Class is declared once.
6)
Object allocates memory when it is created.
Class doesn't allocated memory when it is created.
7)
There are many ways to create object in java such as new keyword, newInstance() method, clone() method, factory method and deserialization.
There is only one way to define class in java using class keyword.



Java Regex
Ø      The Java Regex or Regular Expression is an API to define pattern for searching or manipulating strings.
Ø      It is widely used to define constraint on strings such as password and email validation. After learning java regex tutorial, you will be able to test your own regular expressions by the Java Regex Tester Tool.
Ø      Java Regex API provides 1 interface and 3 classes in java.util.regex package.
java.util.regex package
It provides following classes and interface for regular expressions. The Matcher and Pattern classes are widely used in java regular expression.
1.      MatchResult interface
2.      Matcher class
3.      Pattern class
4.      PatternSyntaxException class

Matcher class
It implements MatchResult interface. It is a regex engine i.e. used to perform match operations on a character sequence.
No.
Method
Description
1
boolean matches()
test whether the regular expression matches the pattern.
2
boolean find()
finds the next expression that matches the pattern.
3
boolean find(int start)
finds the next expression that matches the pattern from the given start number.


Pattern class
It is the compiled version of a regular expression. It is used to define a pattern for the regex engine.
No.
Method
Description
1
static Pattern compile(String regex)
compiles the given regex and return the instance of pattern.
2
Matcher matcher(CharSequence input)
creates a matcher that matches the given input with pattern.
3
static boolean matches(String regex, CharSequence input)
It works as the combination of compile and matcher methods. It compiles the regular expression and matches the given input with the pattern.
4
String[] split(CharSequence input)
splits the given input string around matches of given pattern.
5
String pattern()
returns the regex pattern.

Example of Java Regular Expressions
There are three ways to write the regex example in java.
import java.util.regex.*;  
public class RegexExample1{  
public static void main(String args[]){  
//1st way  
Pattern p = Pattern.compile(".s");//. represents single character  
Matcher m = p.matcher("as");  
boolean b = m.matches();  
  
//2nd way  
boolean b2=Pattern.compile(".s").matcher("as").matches();  
  
//3rd way  
boolean b3 = Pattern.matches(".s", "as");  
  
System.out.println(b+" "+b2+" "+b3);  
}}  
Output
true true true


Regular Expression . Example
The . (dot) represents a single character.
import java.util.regex.*;  
class RegexExample2{  
public static void main(String args[]){  
System.out.println(Pattern.matches(".s", "as"));//true (2nd char is s)  
System.out.println(Pattern.matches(".s", "mk"));//false (2nd char is not s)  
System.out.println(Pattern.matches(".s", "mst"));//false (has more than 2 char)  
System.out.println(Pattern.matches(".s", "amms"));//false (has more than 2 char)  
System.out.println(Pattern.matches("..s", "mas"));//true (3rd char is s)  
}}  


Regex Character classes
No.
Character Class
Description
1
[abc]
a, b, or c (simple class)
2
[^abc]
Any character except a, b, or c (negation)
3
[a-zA-Z]
a through z or A through Z, inclusive (range)
4
[a-d[m-p]]
a through d, or m through p: [a-dm-p] (union)
5
[a-z&&[def]]
d, e, or f (intersection)
6
[a-z&&[^bc]]
a through z, except for b and c: [ad-z] (subtraction)
7
[a-z&&[^m-p]]
a through z, and not m through p: [a-lq-z](subtraction)


Regular Expression Character classes Example
import java.util.regex.*;  
class RegexExample3{  
public static void main(String args[]){  
System.out.println(Pattern.matches("[amn]", "abcd"));//false (not a or m or n)  
System.out.println(Pattern.matches("[amn]", "a"));//true (among a or m or n)  
System.out.println(Pattern.matches("[amn]", "ammmna"));//false (m and a comes more than once)  
}}  


Regex Quantifiers
The quantifiers specify the number of occurrences of a character.
Regex
Description
X?
X occurs once or not at all
X+
X occurs once or more times
X*
X occurs zero or more times
X{n}
X occurs n times only
X{n,}
X occurs n or more times
X{y,z}
X occurs at least y times but less than z times

Regular Expression Character classes and Quantifiers Example
import java.util.regex.*;  
class RegexExample4{  
public static void main(String args[]){  
System.out.println("? quantifier ....");  
System.out.println(Pattern.matches("[amn]?", "a"));//true (a or m or n comes one time)  
System.out.println(Pattern.matches("[amn]?", "aaa"));//false (a comes more than one time)  
System.out.println(Pattern.matches("[amn]?", "aammmnn"));//false (a m and n comes more than one time)  
System.out.println(Pattern.matches("[amn]?", "aazzta"));//false (a comes more than one time)  
System.out.println(Pattern.matches("[amn]?", "am"));//false (a or m or n must come one time)  
  
System.out.println("+ quantifier ....");  
System.out.println(Pattern.matches("[amn]+", "a"));//true (a or m or n once or more times)  
System.out.println(Pattern.matches("[amn]+", "aaa"));//true (a comes more than one time)  
System.out.println(Pattern.matches("[amn]+", "aammmnn"));//true (a or m or n comes more than once)  
System.out.println(Pattern.matches("[amn]+", "aazzta"));//false (z and t are not matching pattern)  
  
System.out.println("* quantifier ....");  
System.out.println(Pattern.matches("[amn]*", "ammmna"));//true (a or m or n may come zero or more times)  
  
}}  


Regex Metacharacters
The regular expression metacharacters work as a short codes.
Regex
Description
.
Any character (may or may not match terminator)
\d
Any digits, short of [0-9]
\D
Any non-digit, short for [^0-9]
\s
Any whitespace character, short for [\t\n\x0B\f\r]
\S
Any non-whitespace character, short for [^\s]
\w
Any word character, short for [a-zA-Z_0-9]
\W
Any non-word character, short for [^\w]
\b
A word boundary
\B
A non word boundary


Regular Expression Metacharacters Example
import java.util.regex.*;  
class RegexExample5{  
public static void main(String args[]){  
System.out.println("metacharacters d....");\\d means digit  
  
System.out.println(Pattern.matches("\\d", "abc"));//false (non-digit)  
System.out.println(Pattern.matches("\\d", "1"));//true (digit and comes once)  
System.out.println(Pattern.matches("\\d", "4443"));//false (digit but comes more than once)  
System.out.println(Pattern.matches("\\d", "323abc"));//false (digit and char)  
  
System.out.println("metacharacters D....");\\D means non-digit  
  
System.out.println(Pattern.matches("\\D", "abc"));//false (non-digit but comes more than once)  
System.out.println(Pattern.matches("\\D", "1"));//false (digit)  
System.out.println(Pattern.matches("\\D", "4443"));//false (digit)  
System.out.println(Pattern.matches("\\D", "323abc"));//false (digit and char)  
System.out.println(Pattern.matches("\\D", "m"));//true (non-digit and comes once)  
  
System.out.println("metacharacters D with quantifier....");  
System.out.println(Pattern.matches("\\D*", "mak"));//true (non-digit and may come 0 or more times)  
  
}}  


Regular Expression Question 1
/*Create a regular expression that accepts alpha numeric characters only. Its 
length must be 6 characters long only.*/  
  
import java.util.regex.*;  
class RegexExample6{  
public static void main(String args[]){  
System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "arun32"));//true  
System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "kkvarun32"));//false (more than 6 char)  
System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "JA2Uk2"));//true  
System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "arun$2"));//false ($ is not matched)  
}}  


Regular Expression Question 2
/*Create a regular expression that accepts 10 digit numeric characters 
 starting with 7, 8 or 9 only.*/  
  
import java.util.regex.*;  
class RegexExample7{  
public static void main(String args[]){  
System.out.println("by character classes and quantifiers ...");  
System.out.println(Pattern.matches("[789]{1}[0-9]{9}", "9953038949"));//true  
System.out.println(Pattern.matches("[789][0-9]{9}", "9953038949"));//true  
  
System.out.println(Pattern.matches("[789][0-9]{9}", "99530389490"));//false (11 characters)  
System.out.println(Pattern.matches("[789][0-9]{9}", "6953038949"));//false (starts from 6)  
System.out.println(Pattern.matches("[789][0-9]{9}", "8853038949"));//true  
  
System.out.println("by metacharacters ...");  
System.out.println(Pattern.matches("[789]{1}\\d{9}", "8853038949"));//true  
System.out.println(Pattern.matches("[789]{1}\\d{9}", "3853038949"));//false (starts from 3)  
  
}}  
Java Regex Finder
import java.io.Console;  
import java.util.regex.Pattern;  
import java.util.regex.Matcher;  
  
public class RegexExample8{  
    public static void main(String[] args){  
        Console console = System.console();  
        if (console == null) {  
            System.err.println("No console.");  
            System.exit(1);  
        }  
        while (true) {  
            Pattern pattern = Pattern.compile(console.readLine("Enter your regex: "));  
            Matcher matcher = pattern.matcher(console.readLine("Enter input string to search: "));  
            boolean found = false;  
            while (matcher.find()) {  
                System.out.println("I found the text "+matcher.group()+" starting at index "+  
                 matcher.start()+" and ending at index "+matcher.end());  
                found = true;  
            }  
            if(!found){  
                System.out.println("No match found.");  
            }  
        }  
    }  
}  
Output:
Enter your regex: java
Enter input string to search: this is java, do you know java
I found the text java starting at index 8 and ending at index 12
I found the text java starting at index 26 and ending at index 30

Java Inner Class
Ø      Java inner class or nested class is a class i.e. declared inside the class or interface.
Ø      We use inner classes to logically group classes and interfaces in one place so that it can be more readable and maintainable.
Ø      Additionally, it can access all the members of outer class including private data members and methods.
Syntax of Inner class
class Java_Outer_class{  
 //code  
 class Java_Inner_class{  
  //code  
 }  
}  
Advantage of java inner classes
There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only.
3) Code Optimization: It requires less code to write.
Do You Know
Ø      What is the internal code generated by the compiler for member inner class ?
Ø      What are the two ways to create annonymous inner class ?
Ø      Can we access the non-final local variable inside the local inner class ?
Ø      How to access the static nested class ?
Ø      Can we define an interface within the class ?
Ø      Can we define a class within the interface ?
Difference between nested class and inner class in Java
Inner class is a part of nested class. Non-static nested classes are known as inner classes.

Types of Nested classes
There are two types of nested classes non-static and static nested classes.The non-static nested classes are also known as inner classes.
Ø      Non-static nested class(inner class)
1.      a)Member inner class
2.      b)Annomynous inner class
3.      c)Local inner class
Ø      Static nested class
Type
Description
Member Inner Class
A class created within class and outside method.
Anonymous Inner Class
A class created for implementing interface or extending class. Its name is decided by the java compiler.
Local Inner Class
A class created within method.
Static Nested Class
A static class created within class.
Nested Interface
An interface created within class or interface.
Java Member inner class
A non-static class that is created inside a class but outside a method is called member inner class.
Syntax:
class Outer{  
 //code  
 class Inner{  
  //code  
 }  
}  
Java Member inner class example
In this example, we are creating msg() method in member inner class that is accessing the private data member of outer class.
class TestMemberOuter1{  
 private int data=30;  
 class Inner{  
  void msg(){System.out.println("data is "+data);}  
 }  
 public static void main(String args[]){  
  TestMemberOuter1 obj=new TestMemberOuter1();  
  TestMemberOuter1.Inner in=obj.new Inner();  
  in.msg();  
 }  
}  
Output:
data is 30
Internal working of Java member inner class
The java compiler creates two class files in case of inner class. The class file name of inner class is "Outer$Inner". If you want to instantiate inner class, you must have to create the instance of outer class. In such case, instance of inner class is created inside the instance of outer class.
Internal code generated by the compiler
The java compiler creates a class file named Outer$Inner in this case. The Member inner class have the reference of Outer class that is why it can access all the data members of Outer class including private.
import java.io.PrintStream;  
class Outer$Inner  
{  
    final Outer this$0;  
    Outer$Inner()  
    {   super();  
        this$0 = Outer.this;  
    }  
    void msg()  
    {  
        System.out.println((new StringBuilder()).append("data is ")  
                    .append(Outer.access$000(Outer.this)).toString());  
    }  
}  

ic Java Anonymous inner class
A class that have no name is known as anonymous inner class in java. It should be used if you have to override method of class or interface. Java Anonymous inner class can be created by two ways:
1.      Class (may be abstract or concrete).
2.      Interface
Java anonymous inner class example using class
abstract class Person{  
  abstract void eat();  
}  
class TestAnonymousInner{  
 public static void main(String args[]){  
  Person p=new Person(){  
  void eat(){System.out.println("nice fruits");}  
  };  
  p.eat();  
 }  
}  
Output:
nice fruits
Internal working of given code
Person p=new Person(){  
void eat(){System.out.println("nice fruits");}  
};  
A class is created but its name is decided by the compiler which extends the Person class and provides the implementation of the eat() method.
An object of Anonymous class is created that is referred by p reference variable of Person type.
Internal class generated by the compiler
import java.io.PrintStream;  
static class TestAnonymousInner$1 extends Person  
{  
   TestAnonymousInner$1(){}  
   void eat()  
    {  
        System.out.println("nice fruits");  
    }  
}  
Java anonymous inner class example using interface
interface Eatable{  
 void eat();  
}  
class TestAnnonymousInner1{  
 public static void main(String args[]){  
 Eatable e=new Eatable(){  
  public void eat(){System.out.println("nice fruits");}  
 };  
 e.eat();  
 }  
}  
Output:
nice fruits
Internal working of given code
It performs two main tasks behind this code:
Eatable p=new Eatable(){  
void eat(){System.out.println("nice fruits");}  
};  
1.      A class is created but its name is decided by the compiler which implements the Eatable interface and provides the implementation of the eat() method.
2.      An object of Anonymous class is created that is referred by p reference variable of Eatable type.
Internal class generated by the compiler
import java.io.PrintStream;  
static class TestAnonymousInner1$1 implements Eatable  
{  
TestAnonymousInner1$1(){}  
void eat(){System.out.println("nice fruits");}  
}  

Java Local inner class
A class i.e. created inside a method is called local inner class in java. If you want to invoke the methods of local inner class, you must instantiate this class inside the method.
Java local inner class example
public class localInner1{  
 private int data=30;//instance variable  
 void display(){  
  class Local{  
   void msg(){System.out.println(data);}  
  }  
  Local l=new Local();  
  l.msg();  
 }  
 public static void main(String args[]){  
  localInner1 obj=new localInner1();  
  obj.display();  
 }  
}  
Output:
30
Internal class generated by the compiler
In such case, compiler creates a class named Simple$1Local that have the reference of the outer class.
import java.io.PrintStream;  
class localInner1$Local  
{  
    final localInner1 this$0;  
    localInner1$Local()  
    {     
        super();  
        this$0 = Simple.this;  
    }  
    void msg()  
    {  
        System.out.println(localInner1.access$000(localInner1.this));  
    }  
}  
Rule: Local variable can't be private, public or protected.
Rules for Java Local Inner class
1) Local inner class cannot be invoked from outside the method.
2) Local inner class cannot access non-final local variable till JDK 1.7. Since JDK 1.8, it is possible to access the non-final local variable in local inner class.
Example of local inner class with local variable
class localInner2{  
 private int data=30;//instance variable  
 void display(){  
  int value=50;//local variable must be final till jdk 1.7 only  
  class Local{  
   void msg(){System.out.println(value);}  
  }  
  Local l=new Local();  
  l.msg();  
 }  
 public static void main(String args[]){  
  localInner2 obj=new localInner2();  
  obj.display();  
 }  
}  
Output:
50
Next
Java static nested class
A static class i.e. created inside a class is called static nested class in java. It cannot access non-static data members and methods. It can be accessed by outer class name.
·        It can access static data members of outer class including private.
·        Static nested class cannot access non-static (instance) data member or method.
Java static nested class example with instance method
class TestOuter1{  
  static int data=30;  
  static class Inner{  
   void msg(){System.out.println("data is "+data);}  
  }  
  public static void main(String args[]){  
  TestOuter1.Inner obj=new TestOuter1.Inner();  
  obj.msg();  
  }  
}  
Output:
data is 30
In this example, you need to create the instance of static nested class because it has instance method msg(). But you don't need to create the object of Outer class because nested class is static and static properties, methods or classes can be accessed without object.
Internal class generated by the compiler
import java.io.PrintStream;  
static class TestOuter1$Inner  
{  
TestOuter1$Inner(){}  
void msg(){  
System.out.println((new StringBuilder()).append("data is ")  
.append(TestOuter1.data).toString());  
}    
}  
Java static nested class example with static method
If you have the static member inside static nested class, you don't need to create instance of static nested class.
class TestOuter2{  
  static int data=30;  
  static class Inner{  
   static void msg(){System.out.println("data is "+data);}  
  }  
  public static void main(String args[]){  
  TestOuter2.Inner.msg();//no need to create the instance of static nested class  
  }  
}  
Output:
data is 30
Next Topic
Java Nested Interface

An interface i.e. declared within another interface or class is known as nested interface. The nested interfaces are used to group related interfaces so that they can be easy to maintain. The nested interface must be referred by the outer interface or class. It can't be accessed directly.

Points to remember for nested interfaces

There are given some points that should be remembered by the java programmer.

Nested interface must be public if it is declared inside the interface but it can have any access modifier if declared within the class.
Nested interfaces are declared static implicitely.
Syntax of nested interface which is declared within the interface

interface interface_name{ 
 ... 
 interface nested_interface_name{ 
  ... 
 } 
}  
Syntax of nested interface which is declared within the class

class class_name{ 
 ... 
 interface nested_interface_name{ 
  ... 
 } 
}  
Example of nested interface which is declared within the interface

In this example, we are going to learn how to declare the nested interface and how we can access it.
interface Showable{ 
  void show(); 
  interface Message{ 
   void msg(); 
  } 
} 
 
class TestNestedInterface1 implements Showable.Message{ 
 public void msg(){System.out.println("Hello nested interface");} 
 
 public static void main(String args[]){ 
  Showable.Message message=new TestNestedInterface1();//upcasting here 
  message.msg(); 
 } 
} 
Test it Now
Output:hello nested interface
As you can see in the above example, we are acessing the Message interface by its outer interface Showable because it cannot be accessed directly. It is just like almirah inside the room, we cannot access the almirah directly because we must enter the room first. In collection frameword, sun microsystem has provided a nested interface Entry. Entry is the subinterface of Map i.e. accessed by Map.Entry.
Internal code generated by the java compiler for nested interface Message
The java compiler internally creates public and static interface as displayed below:.
public static interface Showable$Message 
{ 
  public abstract void msg(); 
} 
Example of nested interface which is declared within the class

Let's see how can we define an interface inside the class and how can we access it.
class A{ 
  interface Message{ 
   void msg(); 
  } 
} 
 
class TestNestedInterface2 implements A.Message{ 
 public void msg(){System.out.println("Hello nested interface");} 
 
 public static void main(String args[]){ 
  A.Message message=new TestNestedInterface2();//upcasting here 
  message.msg(); 
 } 
} 
Test it Now
Output:hello nested interface
Can we define a class inside the interface?

Yes, If we define a class inside the interface, java compiler creates a static nested class. Let's see how can we define a class within the interface:

interface M{ 
  class A{} 
} 


2 comments:

Please write your view and suggestion....