super详解
Super详解
-
super注意点:
1.super调用父类的构造方法,必须在构造方法的第一个!
2.super必须只能出现在子类的方法或者构造方法中!
3.super和this不能同时调用构造方法! -
vs. this:
代表的对象不同:
this: 本身调用者这个对象
super: 代表父类对象的引用
前提:
this: 没有继承也可以使用
super: 只有在继承条件下才可以使用
构造方法:
this(); 本类的构造
super(); 父类的构造 -
package com.oop.demo05; //在Java中,所有的类,都默认直接或间接 继承 Object 类 //Person 人 : 父类 public class Person /* extends Object */ { public Person(String name) { this.name = name; } public Person() { System.out.println("Person无参构造执行了"); } protected String name = "Wang"; //private 修饰的无法被继承 public void print(){ System.out.println("Person"); } } package com.oop.demo05; //Student is a Person :派生类,子类 //子类继承了父类,就会拥有父类的全部方法! //Ctrl + H 打开树结构 public class Student extends Person { public Student() { //隐藏代码:调用了父类的无参构造 super();//调用父类的构造器,必须要在子类构造器的第一行 System.out.println("Student无参构造执行了"); } public Student(String name) { this.name = name; } private String name = "wangzz"; public void print(){ System.out.println("Student"); } public void test1(){ print(); //Student this.print();//Student super.print();//Person } public void test(String name){ System.out.println(name); System.out.println(this.name); System.out.println(super.name); } } package com.oop; import com.oop.demo05.Student; public class Application { public static void main(String[] args) { Student student = new Student(); //student.test("王"); //student.test1(); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!