继承相关代码
父类
package edu.xcdq;
public class Uncle {
private String name;
private int age;
public void faHongbao() {
System.out.println("发红包");
}
public void songche() {
System.out.println("舅舅送车");
}
}
子类一:
package edu.xcdq;
public class UncleOne extends Uncle{
// 独有的方法
public void chouyan() {
System.out.println("大舅喜欢抽烟");
}
}
子类二:
package edu.xcdq;
public class UncleTwo extends Uncle{
// 独有的方法
public void hejiu() {
System.out.println("二舅喜欢喝酒");
}
// 复写 Override 父类中的方法
public void faHongbao() {
System.out.println("夹道中落,不发红包,改送祝福");
}
}
子类三:
package edu.xcdq;
// 多层继承
public class UncleTwoSon extends UncleTwo{
public UncleTwoSon () {
super();// 调用的父类的构造方法
public void faHongbao() {
System.out.println("逆袭了,接着发红包");
}
}
测试类代码
package edu.xcdq;
public class Demo {
public static void main(String[] args) {
UncleOne uncleOne = new UncleOne();
uncleOne.faHongbao(); // 继承的方法
uncleOne.chouyan();
UncleTwo uncleTwo = new UncleTwo();
uncleTwo.faHongbao(); //
uncleTwo.hejiu();
UncleTwoSon uncleTwoSon = new UncleTwoSon();
uncleTwoSon.faHongbao();
uncleTwoSon.songche();
}
}
然后在父类和子类添加构造方法被创建了
代码一在父类添加:
public Uncle () {
System.out.println("舅的构造方法被创建");
}
代码二在子类添加:
public UncleTwo() {
System.out.println("二舅的构造方法被创建");
}
代码三在子类添加:
public UncleTwoSon () {
super();// 调用的父类的构造方法
System.out.println("二舅的儿子类被创建了");
}
然后在测试类代码注释掉
package edu.xcdq;
public class Demo {
public static void main(String[] args) {
/* UncleOne uncleOne = new UncleOne();
uncleOne.faHongbao(); // 继承的方法
uncleOne.chouyan();
UncleTwo uncleTwo = new UncleTwo();
uncleTwo.faHongbao(); //
uncleTwo.hejiu();*/
UncleTwoSon uncleTwoSon = new UncleTwoSon();
/*uncleTwoSon.faHongbao();
uncleTwoSon.songche();*/
}
}