1.继承
父类可以调用子类实例对象,(对于调用抽象类必须使用继承)
模版
//抽象定义一个父类抽象类
abstract class FatherAbstract{
void showFatherAbstract(String color, String name, int age, double serail_abstract){
System.out.println("color = " + color + ", name = " + name + ", age = " + age + ", enum_example = " + serail_abstract);
}
}
2.java的类是一个单继承的类,但不意味着不能继承自己父类的父类,继承是可以继承父类的父类的
这边我使用了父类为构造函数
public class FatherClass extends FatherAbstract{
private final String color;//定义一个不变的变量
private String name;
private int age;
public FatherClass(String color,String name, int age) {
//父类的构造类(必须和父类的名字相同)
this.color = color ;
this.age =age;
this.name =name;
}
public FatherClass(String color) {
//这边我考虑了特殊情况,final定义的不变的变量,必须定义默认值
this.color = color ;
}
public String getColor() {
return color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//前面是get,set方法获取构造函数的变量
public void show(){
//输出打印
System.out.println("名字: "+this.name +"颜色: "+this.color+ "年龄: "+ age);
}
}
3.对于接口来说,是定义方法的模版,一个类可以继承多个接口,(可以把它相当与工具)
interface FatherInterface{
void showInterface(String color, String name, int age ,double serial );
}
4.枚举要定义一个方法需要定义一个抽象类,并重新其方法
enum Fatherenum {
DAY01{
@Override
void showEnum(String color, String name, int age, double enum_example) {
System.out.println("color = " + color + ", name = " + name + ", age = " + age + ", enum_example = " + enum_example);
}
};
abstract void showEnum(String color, String name, int age, double enum_example);
}
5.对比抽象类和接口,其主要区别是 抽象类要写方法体,接口不需要,其次接口是被引用,而抽象类是需要被继承
6.最后复习一下调用
package extendDemo1;
public class ChildrenClass extends FatherClass implements FatherInterface {
//这边因为父类是个构造函数需要传参,子类也需要重构一下
public ChildrenClass(String color, String name, int age) {
super(color, name, age);
}
public ChildrenClass(String color) {
super(color);
}
public static void main(String[] args) {
//父类调用子类实例类
FatherClass fatherClass = new ChildrenClass("黄色", "懂帝", 78);
fatherClass.show();
//引用接口调用被引用接口子类实例类
FatherInterface fatherInterface = new ChildrenClass("紫色");
fatherInterface.showInterface("紫色","罗兰",32,02);
//枚举调用其枚举方法(其是隐性的,不能被继承)
Fatherenum.DAY01.showEnum("土色","黄忠",65,03);
//父类的父类抽象类调用子类实例类(继承也能继承父类的父类)
FatherAbstract childrenClass = new ChildrenClass("红色");
childrenClass.showFatherAbstract("红色","吕布",32,87);
}
//继承了接口必须要重新接口的方法
@Override
public void showInterface(String color, String name, int age, double serial) {
System.out.println("color = " + color + ", name = " + name + ", age = " + age + ", serial = " + serial);
}
}
运行结果