java 类的继承与多态性 /接口多态
1:class
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Animal {
private String name;
Animal(String name) {this.name = name;}
public void enjoy() {
System.out.println("叫声");
}
}
class Cat extends Animal{
private String eyesColor ;
Cat(String name,String eyesColor){super(name);this.eyesColor = eyesColor;}
public void enjoy() {
System.out.println("mimi");
}
}
class Dog extends Animal{
private String furColor;
Dog(String name,String furColor){
super(name);
this.furColor = furColor;
}
public void enjoy(){
System.out.println("汪汪");
}
}
class Lady {
private String name;
private Animal pet;
Lady(String name,Animal pet) {
this.name = name;
this.pet = pet;
}
public void petEnjoy(){
pet.enjoy();
}
}
public class TestAn {
public static void main(String[] args) {
Cat c = new Cat("猫","蓝色");
Lady l1 = new Lady("小丽",c);
l1.petEnjoy();
Dog d = new Dog("狗","黄色");
Lady l2 = new Lady("小丹",d);
l2.petEnjoy();
Animal a = new Animal("老鼠");
Lady l3 = new Lady("小红",a);
l3.petEnjoy();
}
}
2:interface
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
interface Singer {
public void sing();
public void sleep();
}
interface Painter {
public void paint();
public void eat();
}
class Student implements Singer {
private String name;
Student(String name){this.name = name;}
public void study() {
System.out.println("Studying");
}
public String getName() {
return name;
}
public void sing() {
System.out.println("this is student sing");
}
public void sleep() {
System.out.println("this is student sleep");
}
}
class Teacher implements Singer,Painter {
private String name;
Teacher(String name){this.name = name;}
public String getName(){
return name;
}
public void sing() {
System.out.println("this is teacher singing");
}
public void sleep() {
System.out.println("this is teacher Sleeping");
}
public void paint() {
System.out.println("this is teacher painting");
}
public void eat() {
System.out.println("this is teacher eating");
}
//必须实现所有的接口方法,抽象类不必。
}
public class TestImp {
public static void main(String[] args) {
Singer s1 = new Student("xiaodan");
s1.sing();s1.sleep();
Singer s2 = new Teacher("me");
s2.sing();s2.sleep();
Painter p1 = (Painter)s2;
p1.paint();p1.eat();
}
}