详述继承
1、继承的目的
根据访问权限修饰符的不同,子类可以继承父类中某些成员变量和方法,提高了代码的重用性,子类也可以添加新的成员变量和方法
public class Father {
String name;
String id;
String address;
String mobile;
public Object eat() {
System.out.println("正在吃饭.......");
}
}
public class Student extends Father {
int mobile;
public static void main(String[] args) {
Student student = new Student();
student.eat();
}
}
2、什么是继承?
继承是面向对象编程的三大特征之一,是一种基于已有类来创建新类的机制。由继承而得到的类称为子类(或派生类),被继承的类称为父类(或超类)。
Java中每个类只允许有一个父类。语法如下:class <子类> extends <父类>
如果一个类没有显式继承某个类则该类默认继承Object,子类可以继承父类的某些属性或方法(但一定不能被private修饰)
public class Father {
String name;
String id;
String address;
String mobile;
public Object eat() {
System.out.println("正在吃饭.......");
}
}
public class Student extends Father {
public static void main(String[] args) {
Student student = new Student();
student.name = "李雷"
System.out.println(student.name);
student.eat();
}
}
3、怎么继承?
①如果子类中的属性与父类中属性重复,则子类中调用该属性使用的是子类的属性
②如果想要调用父类的属性
<1>子类非静态代码块或非静态方法调用父类中重复的属性使用关键字super。
<2>子类静态代码块或静态方法调用父类中重复的属性需要创建父类对象。
public class Father {
String name;
String id;
String address;
String mobile = "110";
public Object eat() {
System.out.println("正在吃饭.......");
return "rice";
}
}
public class Student extends Father {
long mobile = 120;
public void test() {
System.err.println(mobile);
System.err.println(super.mobile);
}
static {
System.out.println(new Student().mobile);
System.out.println(new Father().mobile);
}
public static void main(String[] args) {
Student student = new Student();
student.eat();
student.test();
System.out.println(student.mobile);
}
4、如果类被final修饰,则该类不能被继承,Java中已有的类(诸如Void、String、Class、Scanner、System、8种基本数据类型对应包装类等类)已经被final修饰,所以这些类不能被继承。
public final class Father {
String name;
String id;
String address;
String mobile;
public Object eat() {
System.out.println("正在吃饭.......");
}
}
public class Student extends Father {
int mobile;
public static void main(String[] args) {
Student student = new Student();
student.eat();
}
}
程序将会报错:The type Student cannot subclass the final class Father