java继承实现
/*** 继承*/
public class Animal { //默认animal集成objectprivate String color;private int age;public Animal(){super();}public Animal(String color,int age){this.color = color;this.age = age;}public void eat(){System.out.println("吃饭");}public void sleep(){System.out.println("睡觉");}public void introduce(){System.out.println(color+"\t"+age);}
}
public class Dog extends Animal{private String nikeName;public Dog(){}public Dog(String color,int age){}public Dog(String color,int age,String nikeName){super(color, age);this.nikeName = nikeName;}public void guard(){System.out.println("看家");}
}
public class Cat extends Animal{private int eyeSight;public Cat(){}public Cat(String color,int age,int eyeSight){super(color, age);this.eyeSight = eyeSight;}public void grabMouse(){System.out.println("猫抓老鼠");}
}
public class Test {public static void main(String[] args) {Dog dog = new Dog("黑色",3,"张三");dog.eat();dog.sleep();dog.introduce();dog.guard();Cat cat = new Cat("白色",3,5);cat.eat();cat.sleep();cat.introduce();cat.grabMouse();}
}
执行代码如下:
继承要点:
1、父类也称作超类、基类。子类也叫作派生类等。
2、java中只有单继承,没有像c++那样的多继承,多继承会引起混乱,使得继承链过于复杂,系统难于维护。
3、子类继承父类,可以得到父类的全部属性和方法(除了父类的构造方法),但是不见得可以直接访问。比如父类私有属性和方法。
4、如果定义一个类时,没有调用extends,则它的父类是:java.lang.object。