Java中的继承与示例

众所周知,
Java是一种面向对象的编程语言(注意,它不是纯OOP语言,因为它支持诸如int,float,double等原始数据类型。)继承是面向对象语言的重要概念,因为它提供了我们的机制允许一个类继承另一个类的特征,继承该特征的类称为派生类或继承类,而继承这些特征的类称为基类超类

注意:基类的所有公共成员和受保护成员均成为派生类的公共成员和受保护成员。

继承的主要用途是提供已编写代码的可重用性。这有助于减少代码行数和程序员的困惑。

Java关键字: extends用于将一个类的功能继承到另一个类。

继承语法:

class Base 
{	/*Body of the Base Class*/		}
class Derived extends Base
{	/* Body of the Derived Class */		}

考虑使用继承的程序:

import java.util.Scanner;
class Headquarters
{
	int totalemployees; //数据成员1-
	String cityname; //数据成员2-
	Scanner KB=new Scanner(System.in);
	void getDetails()
	{
		System.out.println("Enter City Where Headquarters is Sitiuated :");
		cityname=KB.nextLine();
		System.out.println("Enter Total Number of Employees in Headquarters");
		totalemployees=KB.nextInt();
	}

	void showDetails()
	{
		System.out.println("Company Headquarters is Sitiuated in "+cityname+" and has "+totalemployees+" Employees");
	}
}

class Mainbranch extends Headquarters
{
	void getDetails()
	{
		System.out.println("Enter City Where Main Branch is Sitiuated");
		cityname=KB.nextLine();
		System.out.println("Enter The Total Number of Employees In Main Branch");
		totalemployees=KB.nextInt();
	}

	void showDetails()
	{
		System.out.println("Company Main Branch is Sitiuated in "+cityname+" and has "+totalemployees+" Employees");
	}
}

class Company
{
	public static void main(String args[])
	{
		Headquarters H=new Headquarters();
		H.getDetails();
		H.showDetails();	
		Mainbranch M=new Mainbranch();
		M.getDetails(); //Object M,所以方法M调用正确
		M.showDetails();//观察到的代码的可重用性
	}
}

/ *此程序还强调了方法重写的概念* /

单一继承的输出:

Enter City Where Headquarters is Sitiuated :
Delhi
Enter Total Number of Employees in Headquarters
1500
Company Headquarters is Sitiuated in Delhi and has 1500 Employees
Enter City Where Main Branch is Sitiuated
Indore
Enter The Total Number of Employees In Main Branch
500
Company Main Branch is Sitiuated in Indore and has 500 Employees