java语法:01_继承

一、继承的目的

是为了复用代码

  1. 直接用继承的方法、属性
  2. 看不上,自己重写(方法名、参数类型和个数都一样)

二、方法签名

一个方法:确定一个方法跟另一个方法是不是一样,条件:
方法名=方法名
参数类型、个数、顺序=参数类型、个数、顺序

    public void test(){
        
    }
    public void test(String name){
        
    }

    public void test(String b,int a) {
        
    }
    public void test(int a,String b) {
        
    }

三、父类

package com.guoyasoft;

public class Student {
    public String name;
    public int age;
    public String classNo;
    public String shcool;
    
    public void toSchool(){
        System.out.println("我是"+name+",我要去"+shcool+"上学!");
    }
    
    public String toString() {
        return "Student [name=" + name + ", age=" + age + "]";
    }   
}

二、子类

package com.guoyasoft.implement;

public class StudentWL extends Student{

}
package com.guoyasoft.implement;

public class StudentCY extends Student{

}

三、测试

package com.guoyasoft.implement;

public class TestStudent {
    public static void main(String[] args) {
        //父类
        Student wl=new Student();
        wl.name="吴令";
        wl.age=28;
        wl.toSchool();

        //子类
        StudentWL wl1=new StudentWL();
        wl1.name="吴令";
        wl1.age=28;
        wl1.toSchool();
        
        //子类向上转型成父类
        Student wl2=new StudentWL();
        wl2.name="吴令";
        wl2.age=28;
        wl2.toSchool();
    }
}

你可能感兴趣的:(java语法:01_继承)