super 和 方法重写

1、super注意点:

  (1)super调用父类的构造方法, 必须在构造方法的第一个。

  (2)super必须只能出现在子类的方法或者构造方法中。

  (3)super 和 this不能同时调用构造方法。 

2、VS this

  (1)代表的对象不同:

          this:本身调用这个对象。

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

  (2)前提:

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

          super:只能继承条件才可以使用。

  (3)构造方法:

           this():本类的构造。

           super():父类的构造

 

例子:

 1 public class Per {
 2     public static void main(String[] args) {
 3 
 4         Student1 student1 = new Student1();
 5         student1.test("小小王");
 6 
 7         student1.test1();
 8     }
 9 }
10 class Person1{
11     protected String name = "xiaowang";
12 
13     public void print(){
14         System.out.println("person");
15     }
16 
17     public Person1(){
18         System.out.println("Person无参执行了!");
19     }
20 }
21 
22 class Student1 extends Person1{
23     private String name = "小王";
24 
25     public Student1(){
26         //隐藏代码: 调用了父类的无参构造
27         //调用了父类的构造器, 必须要在子类构造器的第一行
28         super();
29         System.out.println("student无参执行了");
30     }
31 
32     public void test(String name){
33         //输出的是这个方法的name
34         System.out.println(name);
35         //输出的是这个类的name
36         System.out.println(this.name);
37         //输出的是父类的name
38         System.out.println(super.name);
39     }
40 
41     public void print1(){
42         System.out.println("student");
43     }
44 
45     public void test1(){
46         print1();
47         this.print();
48         super.print();
49     }
50 
51 }

 

方法重写:

1、重写都是方法的重写,与属性无关。

2、需要继承关系,子类重写父类的方法。

3、方法名必须相同,方法体不同。

4、修饰符:可以扩大不可以缩小  

                    private < default < protected < public

5、抛出的异常,可以被缩小打不能扩大。

6、参数列表必须相同。

7、为什么需要重写:

          父类的功能子类不一定需要,或者不一定满足!

8、不能重写的:

  (1)static方法,它是属于类的,不属于实例。

  (2)final它是常量的。

  (3)private方法,私有的。

posted @ 2022-03-10 15:08  小王同学学编程  阅读(73)  评论(0)    收藏  举报
levels of contents