Java类继承的基本概念和语法

类继承的概念和语法

类继承的概念

  • 根据已有定义来定义新类,新类拥有已有类的所有功能
  • Java只支持类的单继承,每个子类只能有一个直接超类
  • 超类是所有子类的公共属性及方法的集合,子类则是超类的特殊化
  • 继承机制可以提高程序的抽象程度,提高代码的可重用性

超类和子类

  • 子类对象与超类对象存在“是一个…”(或是一种…”)的关系

子类对象

  • 从外部上看,应该包括
    • 与超类相同的接口
    • 可以具有更多的方法和数据成员
  • 其内包含着超类的所有变量和方法

继承的语法

[ClassModifider]calss ClassName extends SuperClassName{
    //类体
}

类继承举例

设有三个类:Person,Employee,Manager。其类层次如图:

public class Person {
	public String name;
	public String getName() { 
		return name; 
	}
} 
public class Employee extends Person { 
	public int employeeNumber; 
	public int getEmployeeNumber() { 
		return employeeNumber; 
	} 
} 
public class Manager extends Employee { 
	public String responsibilities; 
	public String getResponsibilities() { 
		return responsibilities;
	} 
}
public class Exam4_2Test {
	public static void main(String args[]){
		Employee li = new Employee(); 
		li.name = "Li Ming"; 
		li.employeeNumber = 123456; 
		System.out.println(li.getName());
		System.out.println(li.getEmployeeNumber()); 
		Manager he = new Manager(); 
		he.name = "He Xia"; 
		he.employeeNumber = 543469;           
		he.responsibilities = "Internet project"; 
		System.out.println(he.getName()); 
		System.out.println(he.getEmployeeNumber());
		System.out.println(he.getResponsibilities());
	}
}

运行结果:

Li Ming
123456
He Xia
543469
Internet project

访问从超类继承的成员

  • 子类不能直接访问从超类中继承的私有属性及方法,但可使用公有(及保护)方法进行访问
public class B { 
	public int a = 10; 
	private int b = 20; 
	protected int c = 30; 
	public int getB()  { return b; } 
} 
public class A extends B { 
	public int d; 
	public void tryVariables() { 
		System.out.println(a);             //允许
		System.out.println(b);             //不允许
		System.out.println(getB());     //允许
		System.out.println(c);             //允许
	} 
}
发布了9 篇原创文章 · 获赞 4 · 访问量 268

猜你喜欢

转载自blog.csdn.net/weixin_43414889/article/details/105660454