Created
July 13, 2017 22:28
-
-
Save gwpantazes/c26ced888ac7faf44c80c07e36cefd61 to your computer and use it in GitHub Desktop.
Demonstrating that child classes can be in a list of Type Parent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.List; | |
class GrandParent {} | |
class Parent extends GrandParent {} | |
class Child extends Parent {} | |
class Grandchild extends Child {} | |
class Unrelated {} | |
class ParentChildPolymorphismDemo | |
{ | |
public static void main(String[] args) | |
{ | |
List<Parent> list = new ArrayList<>(); | |
// Obviously, we cannot add an unrelated class | |
// list.add(new Unrelated()) | |
// Cannot use ancestor: 'Parent' base class no longer matches | |
// list.add(new GrandParent()); | |
// Intance objects of the class itself and any children are allowed | |
list.add(new Parent()); | |
list.add(new Child()); | |
list.add(new Grandchild()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment