9.Super详解

super注意点:
  1. surper()是调用父类的构造方法,而且必须在构造方法的第一个
  2. super必须只能出现在子类的方法或者构造方法中!
  3. super()和this()不能同时调用构造方法!
  4. Vs this:
代表的对象不同:
this:本身调用者这个对象
super:代表父类对象的引用
前提:
this:没有继承也可以使用
super:只有在继承条件下才可以使用
构造方法:
this();本类的构造
super();父类的构造!

 1 package com.oop.demo05;
 2 
 3 //Java中,所有的类,都默认直接或者间接的继承Object类
 4 //Person 人
 5 public class Person {
 6 
 7     public Person() {
 8         System.out.println("Person无参构造执行了");
 9     }
10 
11     protected String name = "duanfu";
12 
13     public void print() {
14         System.out.println("Person");
15     }
16 }
 1 package com.oop.demo05;
 2 
 3 //学生 is 人:派生类,子类
 4 //子类继承了父类,就会拥有父类的全部方法
 5 public class Student extends Person {
 6 
 7     public Student() {
 8         //隐藏代码;默认调用了父类的无参构造
 9         super();//调用父类的构造器,必须要在子类构造器的第一行
10         System.out.println("Student无参构造执行了");
11     }
12 
13     private String name = "leiwei";
14 
15     public void print() {
16         System.out.println("Student");
17     }
18 
19     public void test1() {
20         print();//Student
21         this.print();//Student
22         super.print();//Person
23     }
24 
25     public void test(String name) {
26         System.out.println(name);//雷伟
27         System.out.println(this.name);//leiwei
28         System.out.println(super.name);//duanfu
29     }
30 
31 }
 1 package com.oop;
 2 
 3 import com.oop.demo05.Student;
 4 
 5 public class Application {
 6 
 7     public static void main(String[] args) {
 8 
 9         Student student = new Student();
10         //student.test("雷伟");
11         student.test1();
12     
13     }
14     
15 }

猜你喜欢

转载自www.cnblogs.com/duanfu/p/12222566.html
今日推荐