我正在读一个Java教程,它说:
抽象类不能实例化,但可以子类化。
这是什么意思?我认为必须实例化才能创建子类?这句话真的把我搞糊涂了,任何帮助都非常感谢。
发布于 2012-11-16 00:24:20
实例化:
AbstractClass a = new AbstractClass(); //illegal
子类:
class ConcreteClass extends AbstractClass { ... }
ConcreteClass c = new ConcreteClass(); //legal
请注意,您还可以执行以下操作:
class ConcreteClass extends AbstractClass { ... }
AbstractClass a = new ConcreteClass(); //legal
发布于 2012-11-16 01:06:15
子类可以获得父类拥有的所有属性/方法,而实例化的类是在内存中创建父类的实例时获得的。
发布于 2012-11-16 00:26:59
当你说实例化时,它意味着你想要创建类的对象。子类是继承子类。例如,
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
https://stackoverflow.com/questions/13408588
复制