继承
继承的代码的和Super的详解
package com.oop.demo01; //person 人 :父类 public class Person{ //publicn //default m默认的 //protected //pribate prinvate int money = 10_0000_0000; //不能单独用子类的东西不然就报错 public void say(){ System.out.println("说了一句话"); } public int getMoney(){ return money; } public void setMoney(int money){ this.money = money; } } //在Java中,所有的类,都默认直接或间接继承Object public class Person/*extends Object*/{ }
package com.oop.demo02; //学生 is 人: 派生类,子类 //子类继承了父类,就会拥有父类的全部方法! public class Student extends Person{ //ctrl+h 单独直接可以选择进入父类 }
package com.oop.demo03; public class Application{ public static void main(String[] args){ Student student = new Student(); student.say(); System.out.println(student.money); } }
注:一个儿子只能有一个爸爸,但是一个爸爸可以有多个儿子
Super详解
package com.oop.demo01; //父类 public class Person{ protected String name = "drumk"; } public void print(){ System.out.ptinyln("Person"); } //私有的东西无法被继承! public Person(){ System.out.println("Person无参执行了"); } }
package com.oop.demo02; //子类 public class Student extends Person{ private String name = "xiaozheng"; public void test(String name){ System.out.println(name);//小郑 System.out.println(this.name);//xiaozheng System.out.println(super.name);//drumk } public void test1(String name){ print();//Student this.print();//student super.print();//person } public void print(){ System.out.println("Student"); } public Student(){ //隐藏代码:调用了父类的无参构造 super();//调用父类的构造器,必须要在子类构造器的第一行 //this(name:"hello");//也同上理 System.out.prrintln("Student无参执行了"); } }
package com.oop.demo03; public class Application{ public static void main(String[] args){ Student student = new Student(); //student.test(name:"小郑"); //studnet.test1(); } }
注:
-
super调用父类的构造方法,必须在构造方法的第一个
-
super必须只能呢出现在子类的方法或者构造方法中
-
super和this不能同时调用构造方法
*super和this的不同:
-
代表对象不同:
-
this:本身调用者这个对象
-
super:代表父类对象的应用
-
-
前提:
-
this:没有继承也能使用
-
super:只能在继承条件才可以使用
-
-
构造方法:
-
this():本类的构造
-
super():父类的构造
-