Java的继承和重写(复习)

Vehicle

public class Vehicle {
    public int wheelNum;   //车轮数量
    // 注意这个方法是私有的
    private void  flameout(){
        System.out.println("车辆熄火");
    }
    public void  lanunch(){
        System.out.println("启动车辆");
    }
}
class  Car extends  Vehicle{
    public  double carHeight;

    public  void  run(){
        System.out.println("启动快,跑起来嗖嗖的");
    }
    public static void main(String[]args){
        Car car = new Car();

        //可以正常调用父类对象中public方法
        car.lanunch();


    }
}

Car

class  Sedan extends Car {
    public  void  manned(){
        System.out.println("可载人...");
    }
    public  static  void  main (String[]ages){
        Sedan sedan = new Sedan();
        // Car继承了Vehicle , Sedan有继承Car,
        //也可以使用Vehicle 中的方法,这个就是多层继承
        sedan.lanunch();
    }
}
结果.png

Parent

public class Parent {
    // 静态变量
    public static String p_staticField = "父类 - 静态变量";
    protected int i = 1;
    protected int j = 8;

    //变量
    public String p_Field = "父类-变量";

    //静态 初始化代码块
    static {
        System.out.println("父类—静态初始化块");
        System.out.println(p_staticField);
    }

    // 普通代码块
    {
        System.out.println("父类 - 初始化块");
        System.out.println(p_Field);
    }
    public  Parent(){
        System.out.println("父类-构造方法");
        System.out.println("i=" + i + ", j =" + j);
        j = 9;
    }
}
class   SubClass  extends  Parent{
    //静态变量
    public  static  String s_staticField = "子类 — 静态变量";
    //变量
    public  String s_Field = "子类- 变量";
    // 静态 初始化代码块
    static{
        System.out.println("子类-静态初始化块");
        System.out.println("s_staticField");
    }
    //普通代码块
    {
        System.out.println("子类—初始化块");
        System.out.println(s_Field);
    }
    public  SubClass(){
        System.out.println("子类-构造方法");
        System.out.println("i=" + i + ", j=" +j);
    }
    public  static  void  main (String[]args){
        new  SubClass();
    }
}
结果·二.png

Animal

public class Animal {
    // 定义动物叫的方法
    public  void  shout(){
        System.out.println("动物发出叫声");
    }
}
class Cat extends Animal{
    //定义狗是怎么叫的
    @Override
    public  void  shout(){
        System.out.println("喵喵喵...");
    }
}
// 测试
class Sample{
    public  static  void  main (String[] args){
        Cat cat = new Cat();
        cat.shout();
    }
}
重写.png

你可能感兴趣的:(Java的继承和重写(复习))