Reputation: 185
I was reading a Java tutorial and it said:
Abstract classes cannot be instantiated, but they can be subclassed.
what does this mean? I thought one had to instantiate in order to create a subclass? This line has really confused me, any and all help is much appreciated.
Upvotes: 2
Views: 1021
Reputation: 11
A subclass can get all the properties/methods that its parent class has, whereas, instantiated class is when you make an instance of that parent class in memory.
Upvotes: 1
Reputation: 7228
When you say instantiated it means you would like to create the object of the class. Sub-class is the inheriting child. For example,
abstract class A{
//Class A is abstract hence, can not be instantiated. The reason being abstract class provides the layout of how the concrete sub-class should behave.
pubic abstract void doSomething();
//This abstract method doSomething is required to be implemented via all the sub-classes. The sub-class B and C implement this method as required.
}
class B extends A{
//Class B is subclass of A
public void doSomething(){ System.out.println("I am class B"); }
}
class C extends A{
//Class C is subclass of A
public void doSomething(){ System.out.println("I am class C"); }
}
if you try to do this, it would generate an exception
A a = new A();
But this would work fine.
B b = new B();
or
A a = new B(); //Note you are not instantiating A, here class A variable is referencing the instance of class B
Upvotes: 0
Reputation: 59283
Instantiate:
AbstractClass a = new AbstractClass(); //illegal
Subclass:
class ConcreteClass extends AbstractClass { ... }
ConcreteClass c = new ConcreteClass(); //legal
You must create a new class that extends the abstract class, implement all of the abstract methods, and then use that new class.
Note that you can also do this:
class ConcreteClass extends AbstractClass { ... }
AbstractClass a = new ConcreteClass(); //legal
Upvotes: 4