AdSense

AdSense3

Tuesday, 30 June 2015

Interview Questions on Abstract Class & Interfaces

1) Can abstract class have constructors in Java?

Yes, abstract class can declare and define constructor in Java. Since you can not create instance of abstract class,  constructor can only be called during constructor chaining, i.e. when you create instance of concrete implementation class. Now some interviewer, ask what is the purpose of constructor, if you can not instantiate abstract class? Well, it can still be used to initialize common variables, which are declared inside abstract class, and used by various implementation. Also even if you don’t provide any constructor, compiler will addefault no argument constructor in abstract class, without that your subclass will not compile, since first statement in any constructor implicitly calls super(), default super class constructor in Java.


2) Can abstract class implements interface in Java? does they require to implement all methods?

Yes, abstract class can implement interface by using implements keyword. Since they are abstract, they don’t need to implement all methods. It’s good practice to provide an abstract base class, along with an interface to declare Type. One example of this is java.util.List interface and corresponding java.util.AbstractList abstract class. Since AbstractList implements all common methods,  concrete implementations like LinkedList and ArrayList are free from burden of implementing all methods, had they implemented List interface directly. It’s best of both world, you can get advantage of interface for declaring type, and flexibility of abstract class to implement common behavior at one place. Effective Java has a nice chapter on how to use interface and abstract class in Java, which is worth reading.



3) Can abstract class be final in Java?

No, abstract class can not be final in Java. Making them final will stop abstract class from being extended, which is the only way to use abstract class. They are also opposite of each other, abstract keyword enforces to extend a class, for using it, on the other handfinal keyword prevents a class from being extended. In real world also, abstract signifies incompleteness, while final is used to demonstrate completeness. Bottom line is, you can not make your class abstract and final in Java, at same time, it’s a compile time error.


4) Can abstract class have static methods in Java?

Yes, abstract class can declare and definstatic methods, nothing prevents from doing that. But, you must follow guidelines for making a method static in Java, as it’s not welcomed in a object oriented design, becausstatic methods can not be overridden in Java. It’s very rare, you see static methods inside abstract class, but as I said, if you have very good reason of doing it, then nothing stops you.


5) Can you create instance of abstract class?

No, you can not create instance of abstract class in Java, they are incomplete. Even though, if your abstract class don’t contain any abstract method, you can not create instance of it. By making a class abstract,  you told compiler that, it’s incomplete and should not be instantiated. Java compiler will throw error, when a code tries to instantiate abstract class.


6) Is it necessary for abstract class to have abstract method?

No, It’s not mandatory for an abstract class to have any abstract method. You can make a class abstract in Java, by just using abstract keyword in class declaration. Compiler will enforce all structural restriction, applied to abstract class, e.g. now allowing to create any instance. By the way, it’s debatable whether you should have abstract method inside abstract class or interface. In my opinion, abstract class should have abstract methods, because that’s the first thing programmer assumes, when he see that class. That would also go nicely along principle of least surprise.


7) Difference between abstract class and interface in Java?

This is the most important and one of the classic Java Interview question. I don’t know, how many times I have seen this question at all most all levels of Java interviews. One reason, which makes this question interesting is ability to produce example. It’s easy to answers questions on core OOPS concepts likAbstractionEncapsulationPolymorphism and Inheritance, but when it comes to subtle points like this, candidate more often fumbled. You can see this post for all syntactical difference between abstract class and interface, but it deserve a post on it’s own.


8) When do you favor abstract class over interface?

This is the follow-up of previous interview questions on abstract class and interface. If you know syntactical difference, you can answer this question quite easily, as they are the one, which drives the decision. Since it’s almost impossible to add a new method on a published interface, it’s better to use abstract class, when evolution is concern. Abstract class in Java evolves better than interface. Similarly, if you have too many methods inside interface, you are creating pain for all it’s implementation, consider providing an abstract class for default implementation. This is the pattern followed in Java collection package, you can see AbstractList provides default implementation for List interface.


9) What is abstract method in Java?

An abstract method is a method without body. You just declare method, without defining it and use abstract keyword in method declaration.  All method declared inside Java Interface are by default abstract. Here is an example of abstract method in Java

                public void abstract printVersion();

Now, In order to implement this method, you need to extend abstract class and override this method.


10) Can abstract class contains main method in Java ?

Yes, abstract class can contaimain method, it just another static method and you can execute Abstract class with main method, until you don’t create any instance.

Saturday, 27 June 2015

super and this- similarities and differences

this(current class)super(super class)
1.It is a keyword used to store current object reference.1.It is a keyword used to store super class object in sub class.
2.Pre define instance variable used to hold current object reference.2.Pre define instance variable used to hold super class object reference through sub class object.
3.Used to separate state of multiple objects of same class and also used to separate local variables and class level variables in a non-static method if both have same name.3.Used to seperate super class and subclass members if both have same name.
4.It must be used explicitly if non-static variables and local variables or parameter name is same.4.It must be used explicitly if super class and sub class members have same names.
5.Can't be referred from static context. It can be printed, means can be called from System.out.println. For example System.out.println(this.x);5.Can't be referred from static context.It can't be printed, means cannot be called from System.out.println. For example System.out.println(super.x); it leads to compile time error.

Friday, 26 June 2015

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
  1. class Vehicle{  
  2.   int speed=50;  
  3. }  
  4. class Bike3 extends Vehicle{  
  5.   int speed=100;  
  6.   void display(){  
  7.    System.out.println(speed);//will print speed of Bike   
  8.   }  
  9.   public static void main(String args[]){  
  10.    Bike3 b=new Bike3();  
  11.    b.display();  
  12. }  
  13. }  

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
  1. //example of super keyword  
  2.   
  3. class Vehicle{  
  4.   int speed=50;  
  5. }  
  6.   
  7. class Bike4 extends Vehicle{  
  8.   int speed=100;  
  9.       
  10.   void display(){  
  11.    System.out.println(super.speed);//will print speed of Vehicle now  
  12.   }  
  13.   public static void main(String args[]){  
  14.    Bike4 b=new Bike4();  
  15.    b.display();  
  16.      
  17. }  
  18. }  
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:
  1. class Vehicle{  
  2.   Vehicle(){System.out.println("Vehicle is created");}  
  3. }  
  4.   
  5. class Bike5 extends Vehicle{  
  6.   Bike5(){  
  7.    super();//will invoke parent class constructor  
  8.    System.out.println("Bike is created");  
  9.   }  
  10.   public static void main(String args[]){  
  11.    Bike5 b=new Bike5();  
  12.         
  13. }  
  14. }  
Output:Vehicle is created
       Bike is created

Note: super() is added in each class constructor automatically by compiler.

java super
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.

  1. class Vehicle{  
  2.   Vehicle(){System.out.println("Vehicle is created");}  
  3. }  
  4.   
  5. class Bike6 extends Vehicle{  
  6.   int speed;  
  7.   Bike6(int speed){  
  8.     this.speed=speed;  
  9.     System.out.println(speed);  
  10.   }  
  11.   public static void main(String args[]){  
  12.    Bike6 b=new Bike6(10);  
  13.  }  
  14. }  

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:
  1. class Person{  
  2. void message(){System.out.println("welcome");}  
  3. }  
  4.   
  5. class Student16 extends Person{  
  6. void message(){System.out.println("welcome to java");}  
  7.   
  8. void display(){  
  9. message();//will invoke current class message() method  
  10. super.message();//will invoke parent class message() method  
  11. }  
  12.   
  13. public static void main(String args[]){  
  14. Student16 s=new Student16();  
  15. s.display();  
  16. }  
  17. }  

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

  1. class Person{  
  2. void message(){System.out.println("welcome");}  
  3. }  
  4.   
  5. class Student17 extends Person{  
  6.   
  7. void display(){  
  8. message();//will invoke parent class message() method  
  9. }  
  10.   
  11. public static void main(String args[]){  
  12. Student17 s=new Student17();  
  13. s.display();  
  14. }  
  15. }  

Output:welcome

Thursday, 25 June 2015

this keyword in java

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.  

The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.               

There can be a lot of usage of java this keyword. In java, this is areference variable that refers to the current object.

Usage of java this keyword

Here is given the 6 usage of java this keyword.
  1. this keyword can be used to refer current class instance variable.
  2. this() can be used to invoke current class constructor.
  3. this keyword can be used to invoke current class method (implicitly)
  4. this can be passed as an argument in the method call.
  5. this can be passed as argument in the constructor call.
  6. this keyword can also be used to return the current class instance.
Suggestion: If you are beginner to java, lookup only two usage of this keyword.
java this keyword


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:
  1. class Student10{  
  2.     int id;  
  3.     String name;  
  4.       
  5.     Student10(int id,String name){  
  6.     id = id;  
  7.     name = name;  
  8.     }  
  9.     void display(){System.out.println(id+" "+name);}  
  10.   
  11.     public static void main(String args[]){  
  12.     Student10 s1 = new Student10(111,"Karan");  
  13.     Student10 s2 = new Student10(321,"Aryan");  
  14.     s1.display();  
  15.     s2.display();  
  16.     }  
  17. }  

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

  1. //example of this keyword  
  2. class Student11{  
  3.     int id;  
  4.     String name;  
  5.       
  6.     Student11(int id,String name){  
  7.     this.id = id;  
  8.     this.name = name;  
  9.     }  
  10.     void display(){System.out.println(id+" "+name);}  
  11.     public static void main(String args[]){  
  12.     Student11 s1 = new Student11(111,"Karan");  
  13.     Student11 s2 = new Student11(222,"Aryan");  
  14.     s1.display();  
  15.     s2.display();  
  16. }  
  17. }  

Output111 Karan
       222 Aryan
this keyword
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

  1. class Student12{  
  2.     int id;  
  3.     String name;  
  4.       
  5.     Student12(int i,String n){  
  6.     id = i;  
  7.     name = n;  
  8.     }  
  9.     void display(){System.out.println(id+" "+name);}  
  10.     public static void main(String args[]){  
  11.     Student12 e1 = new Student12(111,"karan");  
  12.     Student12 e2 = new Student12(222,"Aryan");  
  13.     e1.display();  
  14.     e2.display();  
  15. }  
  16. }  

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.
  1. //Program of this() constructor call (constructor chaining)  
  2.   
  3. class Student13{  
  4.     int id;  
  5.     String name;  
  6.     Student13(){System.out.println("default constructor is invoked");}  
  7.       
  8.     Student13(int id,String name){  
  9.     this ();//it is used to invoked current class constructor.  
  10.     this.id = id;  
  11.     this.name = name;  
  12.     }  
  13.     void display(){System.out.println(id+" "+name);}  
  14.       
  15.     public static void main(String args[]){  
  16.     Student13 e1 = new Student13(111,"karan");  
  17.     Student13 e2 = new Student13(222,"Aryan");  
  18.     e1.display();  
  19.     e2.display();  
  20.    }  
  21. }  

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.
  1. class Student14{  
  2.     int id;  
  3.     String name;  
  4.     String city;  
  5.       
  6.     Student14(int id,String name){  
  7.     this.id = id;  
  8.     this.name = name;  
  9.     }  
  10.     Student14(int id,String name,String city){  
  11.     this(id,name);//now no need to initialize id and name  
  12.     this.city=city;  
  13.     }  
  14.     void display(){System.out.println(id+" "+name+" "+city);}  
  15.       
  16.     public static void main(String args[]){  
  17.     Student14 e1 = new Student14(111,"karan");  
  18.     Student14 e2 = new Student14(222,"Aryan","delhi");  
  19.     e1.display();  
  20.     e2.display();  
  21.    }  
  22. }  

Output:111 Karan null
       222 Aryan delhi

Rule: Call to this() must be the first statement in constructor.

  1. class Student15{  
  2.     int id;  
  3.     String name;  
  4.     Student15(){System.out.println("default constructor is invoked");}  
  5.       
  6.     Student15(int id,String name){  
  7.     id = id;  
  8.     name = name;  
  9.     this ();//must be the first statement  
  10.     }  
  11.     void display(){System.out.println(id+" "+name);}  
  12.       
  13.     public static void main(String args[]){  
  14.     Student15 e1 = new Student15(111,"karan");  
  15.     Student15 e2 = new Student15(222,"Aryan");  
  16.     e1.display();  
  17.     e2.display();  
  18.    }  
  19. }  

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
this keyword
  1. class S{  
  2.   void m(){  
  3.   System.out.println("method is invoked");  
  4.   }  
  5.   void n(){  
  6.   this.m();//no need because compiler does it for you.  
  7.   }  
  8.   void p(){  
  9.   n();//complier will add this to invoke n() method as this.n()  
  10.   }  
  11.   public static void main(String args[]){  
  12.   S s1 = new S();  
  13.   s1.p();  
  14.   }  
  15. }  

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:
  1. class S2{  
  2.   void m(S2 obj){  
  3.   System.out.println("method is invoked");  
  4.   }  
  5.   void p(){  
  6.   m(this);  
  7.   }  
  8.     
  9.   public static void main(String args[]){  
  10.   S2 s1 = new S2();  
  11.   s1.p();  
  12.   }  
  13. }  

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:
  1. class B{  
  2.   A4 obj;  
  3.   B(A4 obj){  
  4.     this.obj=obj;  
  5.   }  
  6.   void display(){  
  7.     System.out.println(obj.data);//using data member of A4 class  
  8.   }  
  9. }  
  10.   
  11. class A4{  
  12.   int data=10;  
  13.   A4(){  
  14.    B b=new B(this);  
  15.    b.display();  
  16.   }  
  17.   public static void main(String args[]){  
  18.    A4 a=new A4();  
  19.   }  
  20. }  

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

  1. return_type method_name(){  
  2. return this;  
  3. }  

Example of this keyword that you return as a statement from the method

  1. class A{  
  2. A getA(){  
  3. return this;  
  4. }  
  5. void msg(){System.out.println("Hello java");}  
  6. }  
  7.   
  8. class Test1{  
  9. public static void main(String args[]){  
  10. new A().getA().msg();  
  11. }  
  12. }  

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.
  1. class A5{  
  2. void m(){  
  3. System.out.println(this);//prints same reference ID  
  4. }  
  5.   
  6. public static void main(String args[]){  
  7. A5 obj=new A5();  
  8. System.out.println(obj);//prints the reference ID  
  9.   
  10. obj.m();  
  11. }  
  12. }  

Output:A5@22b3ea59
       A5@22b3ea59