对象类型声明 [英] Object type declaration

查看:153
本文介绍了对象类型声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以,
当你有类的层次结构如

  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中被覆盖,那么它将调用此覆盖方法。您必须注意不要打破 Liskov替代原则。您可以只访问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.

这篇关于对象类型声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆