Java基础——类的继承

一、为什么要继承:代码更简洁、灵活

父类:

public class Student {

    //属性

    private String name;

    public void setName(String n){

        name = n;
    }

    //学生的行为方法

    public void study(){

        System.out.println(name+”学习”);
    }
}

子类:

public class UNStudent {

}

 

二、继承了什么:属性和方法

子类的对象可以使用父类的方法

父类的对象不可使用子类的方法

public static void main(String[] args) {

    UNStudent s = new UNStudent();

    uns.setName(“iris”);

    Uns.study();

}

 

三、自动转型和强制转型

自动(向上):Student s1 = new UNStudent();

强制:UNStudent s2 = (UNStudent)s2;

实例:

//自动转型在当父类被作为其他方法的参数时较为有效
class teacher(){

    …

    public void teach(Student s){

        System.out.println(s.name+”正在被教”);

    }

}

//可以使用子类作为参数,自动向上转型。
//uns为UNStudent类的对象,可以向上转型为Student,作为参数输入
t.teach(uns);

 

 

四、方法的重写

子类重写父类中的方法:

public class UNStudent {

    //大学生的行为方法

    public void study(){

        System.out.println(name+”进行大学学习。”);

    }

}

 

五、接口

1、接口的定义

public interface 接口名{

    //属性为常量

    public static final int 属性名(大写)=0;

    int 属性名(大写)=0;

    //方法

    public abstract void 属性方法名();

    void 属性方法名();

}



//例子:五子棋Config接口,用于存储静态常量,该常量在其他类中都能用到,不用多次定义和赋值。

public interface Config {

    public static final int X0=30;

    public static final int Y0=30;

    public static final int SIZE=40;

    public static final int LINE=19;

    //保存棋子,二维数组

    public int chessArray[][] = new int[LINE][LINE];

}

final:

放在类前,表示该类——不允许继承

放在方法前,表示该方法——不允许重写

放在常量前,表示该常量——不允许修改

 

 

2、接口的实现

(a)格式

public class 子类 extends 父类 implements 接口1,接口2….{

}

 

(b)方法

接口类要重写所有抽象方法

public class 子类 implements 接口1{

    //实现接口的方法,1需要写public,2去掉abstract
    public void 方法(){
        //方法体
    }
}

//例子:重绘函数
//放大缩小时,窗体自动调用重绘函数,我们重新绘制存在shapeArray中的线条
public void paint(Graphics g) {
        //调用重绘
        super.paint(g);

        int i;
        for(i=0;i<shapeArray.length;i++){
            if(shapeArray[i]!=null){
                shapeArray[i].Redraw(g);
            }
            else
                break;
        }
        System.out.println("重绘");

    }

 

(c)主函数中使用

//创建对象,Person为接口,Student为子类

Person p1 = new Student;

//调用重写父类中的方法

p1.study();

 

 

ps、特例

  • 构造函数:super( );

    无参函数会在子类中自动调用,有参函数需要在子类调用。

class 类名(参数类型 参数名,…){

    super(参数名);

}


//例子:
public UNStudent(String name){

    super(name);

}

    建议在父类中写一个无参构造函数,则不会报错。

发布了63 篇原创文章 · 获赞 23 · 访问量 3万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章