0

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.

3
  • 2
    If I used the first instance, why btn1.setImage(Image img) will give me an error? Because setImage() resides in imageButton class and not Button. Commented Feb 25, 2016 at 16:01
  • how do we read the this line? Button btn1 = new imageButton(); Commented Feb 25, 2016 at 16:02
  • You are creating a object of class Button named btn1 which is initialized with a new object of class imageButton Commented Feb 25, 2016 at 16:04

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your reply, but I still have one uncertainty. Is there any advantage/disadvantage in using this declaration?
@Learnandpractice That is a big question with many answers. The first thing that pops into my mind is to use Button (or what ever the most general type is in a particular situation) unless you know you will need to use specific methods from imageButton (or some other specific subclass). This will make it easier to change the code to switch to EvenBetterImageButton if needed.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.