super关键字、方法重写详解

super关键字详解

代码示例:

Person类

    package com.han.jicheng;
    
    public class Person {
    
        protected String name = "zhangsan1";
    
        public Person() {
            System.out.println("Person无参执行了");
        }
    
        public void print(){
            System.out.println("Person");
        }
    
    }

Student类

    package com.han.jicheng;
    
    public class Student extends Person{
    
        private  String name = "zhangsan2";
    
        public Student() {
            super();//调用父类的构造器,必须在代码第一行
            //this("zhangsan");调用构造器必须在构造器的第一行,且父类的子类的构造器只能调用一个,不能同时调用
            System.out.println("Student无参执行了");
        }
    
        public Student(String name) {
            this.name = name;
        }
    
        public void test(String name){
            System.out.println(name);//zhangsan3
            System.out.println(this.name);//zhangsan2
            System.out.println(super.name);//zhangsan1
        }
    
        public void print(){
            System.out.println("Student");
        }
    
        public void test2(){
            print();//Student
            this.print();//Student
            super.print();//Person
        }
    }

Application类

    package com.han.jicheng;
    
    public class Application {
        public static void main(String[] args) {
            Student student = new Student();
            System.out.println("================================");
            student.test("zhangsan3");
            System.out.println("================================");
            student.test2();
        }
    }

super注意点:

1.super调用父类的构造方法,必须在构造方法的第一个;

2.super只能出现在子类的构造方法或者方法中;

3.super和this不能同时调用构造方法;

Vs this:

1.代表对象不同;

  this:本身调用的对象;

  super:代表父类对象的引用;

2.前提:

  this:没有继承也可以使用;

  super:必须在继承关系中使用;

3.构造方法

  this():本类的构造

  super():父类的构造

方法的重写:需要在继承关系中,子类继承父类的方法;

1.参数名必须相同;

2.参数列表必须相同;

3.方法修饰符发不能为可以扩大,但不能缩小;public>protected>default>private

4.抛出的异常范围,可以被缩小,但不能被扩大;

重写:子类的方法和父类的方法必须一致,方法体不同;

为什么要重写:父类的功能,子类不一定需要,或者不一定满足;

posted @ 2021-12-11 14:47  Dawn_006  阅读(72)  评论(0)    收藏  举报