一、继承关系:子类自动拥有父类非私有属性与方法(java只能单继承)
//继承 public class OOPTest2 { public static void main(String[] args) { Dog d = new Dog(); System.out.println(d.age); d.play(); } } class Animal { protected int age=2; public void play() { System.out.println("animal is playing..."); } } class Dog extends Animal { //没有写子类的属性与方法 //子类自动拥有父类非私有属性和方法 }
二、接口实现多态:同一个接口的不同实现
//多态 public class Test { public static void main(String[] args) { //同一个接口的不同实现 Pet snake = new Snake(); snake.play(); Pet cat = new Cat(); cat.play(); } } //接口 interface Pet { public void play(); } class Snake implements Pet { public void play() { System.out.println("Snake is playing........."); } } class Cat implements Pet { public void play() { System.out.println("Cat is playing..........."); } }