Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conflict of method call using Interface in Java

Tags:

java

interface

Yesterday, I had an interview and I was given the following scenario:

There are 3 classes namely Main.java, MobilePhone.java, DeskPhone.java and one Interface ITelephone.java. powerOn() method is implemented in both classes MobilePhone.java and DeskPhone.java.

How can I call powerOn() method in DeskPhone class after creating an instance of MobilePhone class? In other word, how can I print "You are in DeskPhone class" and "You are in MobilePhone class" in last two calls in Main class?

Is there any another way to solve this problem without renaming powerOn() method in either of class?

Main.java

public class Main {

public static void main(String[] args) {
    ITelephone timsPhone;
    timsPhone = new DeskPhone(123456);
    timsPhone.powerOn();
    timsPhone = new MobilePhone(45678);
   //Question begins here 
    timsPhone.powerOn();
    timsPhone.powerOn();

    }
} 

ITelephone.java

public interface ITelephone {
     void powerOn();
}

MobilePhone.java

public class MobilePhone implements ITelephone{

    private int myNumber;

    public MobilePhone(int myNumber) {
        this.myNumber = myNumber;
    }
    @Override
    public void powerOn() {
        System.out.println("You are in MobilePhone class");
    }
}

DeskPhone.java

public class DeskPhone implements ITelephone {

        private int myNumber;

        public DeskPhone(int myNumber) {
            this.myNumber = myNumber;
        }

        @Override
        public void powerOn() {
            System.out.println("You are in DeskPhone class");
        }
}
like image 899
Jay Parmar Avatar asked Jun 06 '26 16:06

Jay Parmar


1 Answers

Assign the MobilePhone object to a different local variable.

In the current code, once the value of the timsPhone variable is replaced by the MobilePhone object, the DeskPhone object is unreachable and you cannot call its powerOn() method.

Suggested code:

ITelephone timsDeskPhone = new DeskPhone(123456);
timsDeskPhone.powerOn();
ITelephone timsMobilePhone = new MobilePhone(45678);
timsMobilePhone.powerOn();
timsDeskPhone.powerOn();

Output

You are in DeskPhone class
You are in MobilePhone class
You are in DeskPhone class
like image 193
Andreas Avatar answered Jun 09 '26 06:06

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!