25.1.30小记

继承

A extends B : A继承于B

继承可以使子类得到父类的函数(若子类不存在那个名字的函数)
父类有什么就继承什么,并且子类可以增加新东西

父类:

package dome;

public class Item {
    public static void main(String[] args) {

    }

    public void print() {
        System.out.println("Item");
    }
}

子类:

package dome;

public class CD extends Item{
    private String title;
    private String artist;
    private int numofTracks;
    private int playingTime;
    private boolean gotIt = false;
    private String comment;

    public CD(String title, String artist, int numofTracks, int playingTime, String comment) {
        this.title = title;
        this.artist = artist;
        this.numofTracks = numofTracks;
        this.playingTime = playingTime;
        this.comment = comment;
    }
    public static void main(String[] args) {
        CD cd = new CD("abc", "abc", 4, 60, "...");
        cd.print();
    }

//    public void print() {
//        System.out.println("CD:"+ title + ":" + artist);
//    }
}

打印:

Item
package dome;

public class CD extends Item{
    private String title;
    private String artist;
    private int numofTracks;
    private int playingTime;
    private boolean gotIt = false;
    private String comment;

    public CD(String title, String artist, int numofTracks, int playingTime, String comment) {
        this.title = title;
        this.artist = artist;
        this.numofTracks = numofTracks;
        this.playingTime = playingTime;
        this.comment = comment;
    }
    public static void main(String[] args) {
        CD cd = new CD("abc", "abc", 4, 60, "...");
        cd.print();
    }

    public void print() {
        System.out.println("CD:"+ title + ":" + artist);
    }
}

打印:

CD:abc:abc

父类中private的东西,只有父类自己才可以用
protected: 自己可以访问,同一个包里的其他类可以访问,子类可以访问

为Item中的title做一个构造器(对title进行初始化)

在子类中,通过super()传递参数给父类的构造器 eg.(super(title))
如果在子类中没有调用super()则会去寻找father中没有参数的构造器去调用

程序运行顺序 :
father的定义初始化
father的构造器
son的定义初始化
son的构造器

当子类和父类拥有相同名字的变量时,在子类中调用则使用的是子类中的,在父类中调用使用的是父类中的

posted @ 2025-01-31 00:44  Ryan_jxy  阅读(21)  评论(0)    收藏  举报