创建父类Animal.java
package javaoop.ext;
public class Animal {
private String color;
protected String voice;
String name;
public Animal(String color, String voice, String name) {
this.color = color;
this.voice = voice;
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getVoice() {
return voice;
}
public void setVoice(String voice) {
this.voice = voice;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void desc() {
System.out.println(name + "的颜色是" + color + "可以发出" + voice + "声");
}
}
创建子类Cat.java
package javaoop.ext;
public class Cat extends Animal {
private String run;
private final int NUM = 10;
public Cat(String color, String voice, String name, String run) {
this("黄色", "沙哑的", "小黑");
this.run = run;
}
public Cat(String color, String voice, String name) {
super(color, voice, name);
}
public void function() {
System.out.println(this.name + "捕老鼠");
}
public void test() {
super.desc();
}
}
创建子类Dog.java
package javaoop.ext;
public class Dog extends Animal {
private String eat = "吃屎";
private static String hair = "光滑";
public Dog(String color, String voice, String name) {
super(color, voice, name);
}
public void function() {
System.out.println(super.getName() + "会看门");
}
public static void test() {
System.out.println("哈哈");
}
public static void method() {
test();
System.out.println(hair);
}
static {
method();
}
}
测试类Test01.java
package javaoop.ext;
public class Test01 {
public static void main(String[] args) {
Cat cat1 = new Cat("粉色", "甜甜的", "小猫");
Cat cat2 = new Cat("橘黄色", "尖锐的", "小苗", "跑呀");
Animal dog1 = new Dog("黄色", "旺旺呀", "小狗");
Dog dog3 = (Dog) dog1;
dog3.function();
Dog dog2 = new Dog("黑色", "旺旺啊", "小狗");
System.out.println("调猫类测试方法");
cat1.test();
System.out.println("调猫类测试方法");
cat2.test();
System.out.println("调狗的父类方法");
dog1.desc();
System.out.println("调狗类自己方法");
dog2.function();
}
}
运行结果:
|