java入门总结part2

继承(扩展)性(涉及supper)

用extends来实现,具体写法:

package javalearn;
class Person{//定义的父类

    String name;
     int age;
    
    public Person(String name,int age) {//父类的构造方法
        this.name=name;
        this.age=age;
    }
    public void tell() {
        System.out.println(name+" "+age);
    }


}
class Student extends Person {//子类Student继承父类的所有属性及方法
   public Student(String name, int age) {//因为父类写了构造方法所以子类必须要写构造方法然后利用super来继承
        super(name, age);
    }
   int score;
   public void say() {
        System.out.println(score);
    }
}
public class Learn {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Student sub1 = new Student(null, 0);//有构造方法必须传参,通过建立子类实例来使用父类里的属性及方法
        sub1.age=30;
        sub1.name="李斯";
        sub1.score=100;
        sub1.tell();
        sub1.say();
    }

}

运行结果:李斯 30

                   100

重写与重载(包含super)

重写使用方法:

package javalearn;(不含super)
class Person{

    public void tell() {
        System.out.println("我是父类的方法");
    }


}
class Student extends Person {
 
   public void tell() {//名字与父类的方法一样
        System.out.println("我是子类重写了父类的方法");
    }
}
public class Learn {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Student sub1 = new Student();
        sub1.tell();
        
    }

}

运行结果:我是子类重写了父类的方法

package javalearn;(包含super)
class Person{

    public void tell() {
        System.out.println("我是父类的方法");
    }


}
class Student extends Person {
 
   public void tell() {
       super.tell();//加了这一句就不会被子类覆盖
        System.out.println("我是子类重写了父类的方法");
    }


}
public class Learn {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Student sub1 = new Student();
        sub1.tell();
        
    }

}

运行结果:我是父类的方法

                  我是子类重写了父类的方法

重载使用方法:就是在一个对象也就是一个类里写几个相同名字的方法,但是参数形式或个数不同,以此来根据传递的参数不同

                          来在名字相同的方法中选择符合要求的执行。

上一个图:

 代码演示:

package javalearn;
class Person{

    public void tell(int a) {
        System.out.println("我是方法一,我符合规则我输出,其他方法不输出");
    }
    public void tell(String name) {
        System.out.println("我是方法二,我符合规则我输出,其他方法不输出");
    }
    public void tell(int a,String name) {
        System.out.println("我是方法三,我符合规则我输出,其他方法不输出");
    }


}

public class Learn {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Person per=new Person();
        per.tell(3);//只调用了方法一
        per.tell("李斯");//只调用了方法二
        per.tell(3,"李斯");//只调用了方法三
        
    }

}


运行结果:

我是方法一,我符合规则我输出,其他方法不输出
我是方法二,我符合规则我输出,其他方法不输出
我是方法三,我符合规则我输出,其他方法不输出

明天继续抽象类与接口,wait。。。。。。。。

猜你喜欢

转载自blog.csdn.net/qq_41767383/article/details/82760960