package j1210.cls;
// 如果一个程序需要输入数据, 则程序流程预先无法确定
// - 从标准输入读取数据
// - 经由程序参数
// - 从文件 / 网络等读取数据
// - 根据时间
// 语义
public class Animal /* 没有显式指定父类, 则父类是 */{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String cry() {
return "...";
}
public Animal(String name) {
super();
this.name = name;
System.out.println("Animal created, name = " + name);
}
public Animal() {
System.out.println("Animal created, no parameters");
}
public static void main(String[] args) {
Animal a = new Animal("Xiaobai");
System.out.println(a.getName());
System.out.println(a.cry());
Cat c = new Cat("Xiaohei", "Black");
System.out.println(c.getName() + " is " + c.getColor());
System.out.println(c.cry());
Animal d = new Dog();
Animal e; // 声明对象引用的类型为较高层次 (父类) 的类型
if (System.currentTimeMillis() < 0) {
e = c; // 将子类的对象交给该引用
} else {
e = new Parrot("Packy");
}
System.out.println(d.cry());
System.out.println(e.cry()); // 对于在编码时无法预先确定具体类型的情况, 采用多态实现
}
}
// 一只猫是一个动物
// 继承是面向对象的基础 <- 多态建立在继承的基础之上
// 子类拥有父类的一切成员方法 / 成员属性
class Cat extends Animal {
// 猫是动物
// 动物有名字
// ---
// 猫有名字
// 如果设计中, 某个因素没有本质的区别, 应该使用属性
// class BlackCat extends Cat
// class YellowCat extends Cat
// class WhiteCat extends Cat
private String color;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public Cat(String name) {
// 子类构造函数必须在第一句话
// - 调用父类的构造函数
// - 或者调用子类其他构造方法 (代理构造)
// - 否则, 则默认为 super() 调用父类无参构造方法, 如果父类没有无参构造方法, 则报错
super(name);
System.out.println("Cat created, name = " + name);
}
public Cat() {
super(); // 可省略
System.out.println("Cat created, no parameters");
}
public Cat(String name, String color) {
// 调用自身的另外一个构造方法来构造对象 (代理构造)
this(name);
System.out.println("Cat created, color = " + color);
this.color = color;
}
// 覆盖 / 重写
// 子类中出现名字以及形式参数列表与父类完全一致的函数
// 允许子类重写父类的成员方法, 实现完全不同的功能
public String cry() {
return "moew";
}
}
// 一条狗是一个动物
class Dog extends Animal {
// 如果类中没有显示编写构造方法, 则类中会存在一个默认的无参构造方法, 方法体仅有一句话 super();
public String cry() {
return "wang";
}
}
class Parrot extends Animal {
public Parrot(String name) {
super(name);
}
// 需求中, 子类成员方法的实现与父类有本质的区别, 才应该使用覆盖
public String cry() {
return "My name is " + getName();
}
}
java 面向对象—继承
最新推荐文章于 2022-11-25 07:30:00 发布