Java入门——day41

1.继承示例:

//动物类
public class Animal {
    private String name; //姓名
    private int age;     //年龄
    
    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;
    }
    public void say() {
        System.out.println("我是一个动物,我叫"+this.getName()+",我的年龄是"+this.getAge());
    }
}
//定义Dog类,继承Animal类
public class Dog extends Animal {
    // 重写父类的say()方法
    public void say() {
        System.out.println("我是一只狗,我叫" + this.getName() + ",我的年龄是" + this.getAge());
    }

    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.setName("Pick");
        dog.setAge(2);
        dog.say();
    }
}

 2.生成get、set方法的快捷方式:Alt+Shifl+s

 3.对象实例化以及super关键字示例

//定义Dog类,继承Animal类
public class Dog extends Animal {
    private String home; // 地址
    // 无参构造方法

    public Dog() {
        super();
        System.out.println("子类无参构造方法");
    }

    // 有参构造方法
    public Dog(String name, int age, String home) {
        super(name, age);
        this.home = home;
        System.out.println("子类有参构造方法");
    }

    public String getHome() {
        return home;
    }

    public void setHome(String home) {
        this.home = home;
    }

    // 重写父类的say()方法
    public void say() {
        System.out.println("我是一只狗,我叫" + this.getName() + ",我的年龄是" + this.getAge() + ",我来自" + this.getHome());
    }

    public static void main(String[] args) {
        Dog dog = new Dog("Mini", 3, "火星");
        dog.say();
    }
}

 4.定义静态常量:static final double PI=3.1415926

原文地址:https://www.cnblogs.com/znjy/p/13510586.html