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");
}
}