Java Note 11 Inheritance | 继承

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 :

  1. extends 有 s
  2. 没有carry parameters
  3. 这是一个单继承

关键字 implements
  • Syntax
public interface Shape{
//...
}

public interface Color{
//```
}

public class Object implements Shape, Color{}
  • 接口
  • 可以继承多个接口

继承的种类
  1. 单继承: Father->Child
public class Father{
//some code
}

public class Child extends Father{
//some code
}
  1. 多继承: Father->Father1->Child
    !! NOT LEGSL IN JAVA
public class Father{
some code
}

public class Father1{
//some code
}

public class Child extends Father, Father1{
//...
}
  1. 多重继承: Father->Child->GrandChild
public class Father{
//some code
}

public class Child extends Father{
//some code
}

public class GrandChild extends Child{
//some code here
}
  1. (多肽)下一章内容

Java继承的好处
  1. 避免代码冗余,提高代码利用率
  2. 便于后期修改维护
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值