abstract class A {
public void disp() {
System.out.print("Abstract");
}
}
public class B {
public static void main(String args[]) {
A object = new A(){ };
object.disp();
}
}
I am aware that Abstract classes cannot be instantiated, but confused on this code. Actually what this code mean ?
Abstract class, we have heard that abstract class are classes which can have abstract methods and it can't be instantiated. We cannot instantiate an abstract class in Java because it is abstract, it is not complete, hence it cannot be used.
Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract .
clone() will not work on interfaces and abstract classes. The only way to use the Object. clone() method is if the class of an object is known, i.e., we cannot access the clone() method on an abstract type since most interfaces and abstract classes in Java do not specify a public clone() method.
Abstract Class is Half Define Class. Abstract class not allowed to create an Instance (Object). So, we can not create any instance then answer is 0. There are no objects for abstract class.
The subtlety here is in the "{}". It means you explicitly provide an anonymous implementation for the missing parts (the missing parts are abstract methods) of the abstract class A
allowing you to instantiate it.
But there's no abstract method in A
, therefore the anonymous implementation is empty.
Example showing the behaviour with at least one abstract method:
public abstract class A {
public abstract void bar();
public void disp() { System.out.print("Abstract"); }
}
public class B {
public static void main(String args[]) {
A object = new A() {
@Override public void bar() { System.out.print("bar"); }
};
object.disp(); //prints "Abstract"
object.bar(); //prints "bar"
}
}
This is called an anonymous inner class. You are not instantiating the abstract class, you are instantiating the concrete anonymous inner class which extends the abstract class. Of course, in order for this to be allowed, the anonymous inner class must provide implementations for all the abstract members of the abstract superclass … which it does in this case, because the abstract superclass has no abstract members.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With