本文共 2669 字,大约阅读时间需要 8 分钟。
继承:
作用:代码复用
通过extends实现继承
超类/基类/父类:共有的属性和行为
派生类/子类:特有的属性和行为
派生类可以访问:超类的+派生类的,超类不能访问派生类的
一个超类可以有多个派生类,一个派生类只能有一个超类---------单一继承
具有传递性
java规定:构造派生类之前必须先构造超类
在派生类的构造方法中若没有调用超类的构造方法,则默认super()调用超类的无参构造方法
在派生类的构造方法中若自己调用了超类的构造方法,则不再默认提供
注意:super()调用超类构造方法,必须位于派生类构造方法中的第1行
public class Person { String name; int age; String address; Person(String name,int age,String address){ this.name = name; this.age = age; this.address = address; } void eat(){ System.out.println(name+"正在吃饭..."); } void sleep(){ System.out.println(name+"正在睡觉..."); } void sayHi(){ System.out.println("大家好,我叫"+name+",今年"+age+"岁了,家住"+address); }}public class Student extends Person{ String className; String stuId; Student(String name,int age,String address,String className,String stuId){ super(name,age,address); //传递的是name/age/address的值 this.className = className; this.stuId = stuId; } void study(){ System.out.println(name+"正在学习..."); }}public class Teacher extends Person{ double salary; Teacher(String name,int age,String address,double salary){ super(name,age,address); this.salary = salary; } void teach(){ System.out.println(name+"正在讲课..."); }}public class Doctor extends Person { String title; Doctor(String name,int age,String address,String title){ super(name,age,address); this.title = title; } void cut(){ System.out.println(name+"正在做手术..."); }}public class ExtendsTest { public static void main(String[] args) { Student zs = new Student("张三",25,"廊坊","jsd2302","001"); zs.eat(); zs.sleep(); zs.sayHi(); zs.study(); Teacher ls = new Teacher("李四",35,"佳木斯",6000.0); ls.eat(); ls.sleep(); ls.sayHi(); ls.teach(); Doctor ww = new Doctor("王五",46,"山东","主任医师"); ww.eat(); ww.sleep(); ww.sayHi(); ww.cut(); }}
super:指代当前对象的超类对象
super.成员变量名-------------------------访问超类的成员变量
当超类成员变量和派生类成员变量同名时,super指超类的,this指派生类的
若没有同名现象,则写super和this是一样的
super.方法名()------------------------------调用超类的方法
super()----------------------------------------调用超类的构造方法
public class SuperDemo { public static void main(String[] args) { Boo o = new Boo(); }}//在派生类的构造方法中若自己调用了超类的构造方法,则不再默认提供class Coo{ Coo(int a){ }}class Doo extends Coo{ Doo(){ super(5); } /* //如下代码为默认的 Doo(){ super(); } */}class Aoo{ Aoo(){ System.out.println("超类构造方法"); }}class Boo extends Aoo{ Boo(){ super(); //默认的,调用超类的无参构造方法 System.out.println("派生类构造方法"); }}
转载地址:http://ytqcuy.baihongyu.com/