问题描述
好的,所以,
当你有类的层次结构如
public class A {。 ..}
和
public class B extends A {...}
...当你创建对象时,有什么区别:
A object = new A();
A object = new B();
B object = new B();感谢您的时间。 >解决方案 A object = new A();
您正在创建一个 A实例
引用类型A.您只能访问A方法/属性和父类方法/属性。
A object = new B );
您正在参考中创建 B实例
这样, object
可以以多态方式工作,例如,如果你使 object.method()
和方法
在B中被覆盖,那么它将调用此覆盖方法。您必须注意不要打破。您可以只访问A方法/属性和父项方法/属性。这是当你只需要超类型契约时的首选方法。
B object = new B
您正在创建一个 B实例
类型 B
的引用变量。您可以只访问B方法/属性和父项方法/属性。
Ok.. So,When you have a hierarchy of classes such as
public class A {...}
and,
public class B extends A {...}
...When you create objects, what is the difference between:
A object = new A();
A object = new B();
B object = new B();
Thank you for your time.
解决方案 A object = new A();
You are creating an A instance
in a reference of type A. You may can access only A methods/properties and parents methods/properties.
A object = new B();
You are creating B instance
in a reference of type A. In this way object
could behave in a polymorphic way, for example if you make object.method()
and method
is overriden in B then it will call this override method. You have to take care in not to break the Liskov Substitution Principle. You may can access only A methods/properties and parents methods/properties. This is the preferred way when you only need supertype contract.
B object = new B();
You are creating a B instance
in a reference variable of type B
. You may can access only B methods/properties and parents methods/properties.
这篇关于对象类型声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!