简体   繁体   English

Java中的继承和多态

[英]Inheritance and Polymorphism in Java

Suppose I have two classes as following: 假设我有两个类,如下所示:

public class Button{
       public void onClick(){ do something...}}

public class imageButton extends Button{
       public void onClick(){...}
       public void setImage(Image img){...}}

I know that I can declare a variable like this 我知道我可以这样声明一个变量

Button btn1 = new imageButton();

or 要么

imageButton btn2 = new imageButton():

but what are the differences? 但是有什么区别呢? What exactly is the datatype of the first instance? 第一个实例的数据类型到底是什么? If I used the first instance, why btn1.setImage(Image img) will give me an error? 如果使用第一个实例,为什么btn1.setImage(Image img)会给我一个错误?

Thank you. 谢谢。

Button btn1 = new imageButton(); What exactly is the datatype of the first instance? 第一个实例的数据类型到底是什么?

It is an imageButton , but you will only have access to the methods defined in Button when using the reference btn1 . 这是一个imageButton ,但是使用引用btn1时,您只能访问Button定义的方法。 If you want to treat it as an imageButton , you'll have to cast it. 如果要将其视为imageButton ,则必须imageButton转换它。

If I used the first instance, why btn1.setImage(Image img) will give me an error? 如果使用第一个实例,为什么btn1.setImage(Image img)会给我一个错误?

Because you declared that you want to treat the object as a Button . 因为您声明要将该对象视为Button

with Button btn1 = new imageButton(); 使用按钮btn1 = new imageButton(); you are creating an instance of imageButton but since you datatype is Button it will only take the properties that are included in Button, you cant use btn1.setImage() because btn1 is a Button Type. 您正在创建imageButton的实例,但是由于您的数据类型是Button,所以它将仅使用Button中包含的属性,因此您不能使用btn1.setImage(),因为btn1是Button Type。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM