Learn and practice
Learn and practice

Reputation: 101

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?

Thank you.

Upvotes: 0

Views: 83

Answers (2)

Cristian Cam G
Cristian Cam G

Reputation: 362

with Button 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.

Upvotes: 0

bradimus
bradimus

Reputation: 2523

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. If you want to treat it as an imageButton, you'll have to cast it.

If I used the first instance, why btn1.setImage(Image img) will give me an error?

Because you declared that you want to treat the object as a Button.

Upvotes: 3

Related Questions