Polymorphism
- Eclipse: Oxygen
- Java: 1.8
This tutorial deals with the concept of polymorphism. Polymorphism in simple words means to have multiple forms of a single entity.
In the previous example when a note8 object call features methods by different scopes (class scope, one of Phone and one of SamsungNote8) we obtain different outputs.
1 2 3 4 5 6 7 |
public class Nokia3310 extends Phone { public Nokia3310(String model) { super(model); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class Phone { private String model; public Phone(String model) { this.model = model; } public void features(){ System.out.println("Feature phone"); } public String getModel() { return model; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class SamsungNote8 extends Phone{ public SamsungNote8(String model) { super(model); } public void features(){ System.out.println("Andriod flagship"); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class Hello { public static void main(String[] args) { Phone note8 = new SamsungNote8("Note 8"); System.out.println(note8.getModel()); note8.features(); Phone nokia3310 = new Nokia3310("Nokia 3310"); System.out.println(nokia3310.getModel()); nokia3310.features(); } } |
Output
Andriod flagship
Nokia 3310
Feature phone
Here another such example of the same function depicting a different output when referenced by the object of the different class is shown.
Here the same example as above is taken in an altogether different function outside the main function which has a return type of Phone class.
1 2 3 4 5 6 7 |
public class Nokia extends Phone { public Nokia(String model) { super(model); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class Phone { private String model; public Phone(String model) { this.model = model; } public void features(){ System.out.println("Feature phone"); } public String getModel() { return model; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class Samsung extends Phone{ public Samsung(String model) { super(model); } public void features(){ System.out.println("Andriod flagship"); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public class Hello { public static void main(String[] args) { Phone nokia3310 = new Hello().phone(1); System.out.println(nokia3310.getModel()); nokia3310.features(); Phone note8 = new Hello().phone(2); System.out.println(note8.getModel()); note8.features(); } public Phone phone(int dailyDriver){ switch(dailyDriver){ case 1: return new Nokia("3310"); case 2: return new Samsung("Note 5"); } return null; } } |
Output
3310
Feature phone
Note 5
Andriod flagship
Contributed by: Poonam Tomar