Hi all,
I'am looking for someone who can clear my doubt that struck to my little brain. I read that we cannot create an object for an abstract class. But I deliberately could create an object of the same.
Please throw a glance at the code below:
//============================================================
public abstract class MyAbstractClass {
public MyAbstractClass(){
System.out.println("creating MyAbstractClass object");
}
public abstract
String methodOne();
public abstract String methodTwo();
public static void main(String a[]){
MyAbstractClass myAbstractClass = new MyAbstractClass(){
public String methodOne() {
return "THIS IS METHOD ONE";
}
public String methodTwo() {
return "THIS IS METHOD TWO";
}
}; // end of MyAbstractClass creation;
System.out.println(myAbstractClass.methodOne());
System.out.println(myAbstractClass.methodTwo());
} // end of main
} // end of MyAbstractClass
//============================================================
This is the output I got:
creating MyAbstractClass object
THIS IS METHOD ONE
THIS IS METHOD TWO
//============================================================
Can I correlate this way:
Implementing an interface would require to define all the methods of the interface, whether they are required or not.
Example:
MouseListener (Interface)
Extending an abstract class, programmer would define methods of his choice.
Example:
MouseAdapter (Abstract Class)
In between, both Interfaces as well as Abstract classes cannot be instantiated in
java. By default, an Interface itself is abstract and all the methods in an Interface are abstract. An Abstract class may or maynot have Abstract methods.
This was my answer for the difference between interface and abstract class in an interview. But the interviewer was not satisfied with my explanation
He asked me to think out of the box!
Would any one tell me the actual use of an abstract class over interfaces in java.
Regards,
SAi.