Skip to content

Instantly share code, notes, and snippets.

@gwpantazes
Created July 13, 2017 22:28
Show Gist options
  • Save gwpantazes/c26ced888ac7faf44c80c07e36cefd61 to your computer and use it in GitHub Desktop.
Save gwpantazes/c26ced888ac7faf44c80c07e36cefd61 to your computer and use it in GitHub Desktop.
Demonstrating that child classes can be in a list of Type Parent
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