我正在阅读 Java 教程,它说:
抽象类不能被实例化,但它们可以被子类化。
这是什么意思?我认为必须实例化才能创建子类?这条线真的让我很困惑,非常感谢任何和所有的帮助。
实例化:
AbstractClass a = new AbstractClass(); //illegal
子类:
class ConcreteClass extends AbstractClass { ... }
ConcreteClass c = new ConcreteClass(); //legal
您必须创建一个扩展抽象类的新类,实现所有抽象方法,然后使用该新类。
请注意,您也可以这样做:
class ConcreteClass extends AbstractClass { ... }
AbstractClass a = new ConcreteClass(); //legal
子类可以获取其父类具有的所有属性/方法,而实例化类是在您在内存中创建该父类的实例时。
当你说实例化时,它意味着你想创建类的对象。子类是继承的孩子。例如,
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