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