Inheritance
- A subclass is a class that extends another class
- inherits state and behavior from all its
ancestor. - Subclass inherits all, except private superclasses members and constractor (invoke)
- The superclass refers to a direct ancestor.
- java.lang.Object(bydefault)
- Derived class 继承所有不是private的method 和property
- Derived class 可以重兴实现(override) Base class 的方法;可以拓展
关键字 super
- 访问父类成员
- 调用Base 方法
- 可以引用当前obj的Base
- 当调用父类有参数的constructor时,必须使用super
- 不用super()->invoke no args by default
package practice7;
public class practice {
public class BaseClass {
BaseClass() {
System.out.print("base cons no args");
}
BaseClass(int num) {
System.out.print("base cons with args" + num);
num = 0;
}
void test() {
System.out.print("base");
}
}
public class DerivedClass extends BaseClass {
DerivedClass() {
System.out.print("derived cons no args");
}
DerivedClass(int num) {
super(10);
System.out.print("derived cons with args" + num);
num = 1;
}
void test() {
System.out.print("derived");
}
void dtest() {
this.test();
super.test();
}
}
public static void main(String[] args) {
BaseClass bclass = new BaseClass();
BaseClass bclass1 = new BaseClass(5);
bclass.test(); // base
DerivedClass dclass = new DerivedClass();
DerivedClass dclass1 = new DerivedClass(6);
dclass.test(); // derived; base;
}
}
关键字extends
- Syntax
public class BaseClass{
//some code
}
public class DerivedClasee extends BaseClass{
//some code
}
Important :
- extends 有 s
- 没有carry parameters
- 这是一个单继承
关键字 implements
- Syntax
public interface Shape{
//...
}
public interface Color{
//```
}
public class Object implements Shape, Color{}
- 接口
- 可以继承多个接口
继承的种类
- 单继承: Father->Child
public class Father{
//some code
}
public class Child extends Father{
//some code
}
- 多继承: Father->Father1->Child
!! NOT LEGSL IN JAVA
public class Father{
some code
}
public class Father1{
//some code
}
public class Child extends Father, Father1{
//...
}
- 多重继承: Father->Child->GrandChild
public class Father{
//some code
}
public class Child extends Father{
//some code
}
public class GrandChild extends Child{
//some code here
}
- (多肽)下一章内容
Java继承的好处
- 避免代码冗余,提高代码利用率
- 便于后期修改维护