继承是面向对象编程的一块基石。它允许创建分等级层次的类。在代码中使用继承,你能使用一个通用类,它定义了一系列相关项目的特性。该类可以被其他的类继承,并且拥有一些自己特性的东西。在JAVA术语中,被继承的类叫做超类(SuperClass),继承超类的类叫做子类(SubClass).
要继承一个类,只要用extends关键字把一个类的定义合并到另一个类中即可。
来看一下下面的测试代码。
package
pkg2;
class A {
int i,j;
void showij()
{
System.out.println( " i and j: " + (i + j));
}
}
class B extends A
{
int k;
void showk()
{
System.out.println( " k : " + k);
}
void sum()
{
System.out.println( " i+j+k : " + (i + j + k));
}
}
class simpleInheritance {
public static void main(String args[])
{
A supoa = new A();
B supob = new B();
supoa.i = 3 ;
supoa.j = 2 ;
System.out.println( " centens of supoa: " );
supoa.showij();
System.out.println();
supob.i = 7 ;
supob.j = 8 ;
supob.k = 10 ;
System.out.println( " centens of supob: " );
supob.showij();
supob.showk();
System.out.println();
System.out.println( " sum of i ,j and k in supob: " );
supob.sum();
}
}
class A {
int i,j;
void showij()
{
System.out.println( " i and j: " + (i + j));
}
}
class B extends A
{
int k;
void showk()
{
System.out.println( " k : " + k);
}
void sum()
{
System.out.println( " i+j+k : " + (i + j + k));
}
}
class simpleInheritance {
public static void main(String args[])
{
A supoa = new A();
B supob = new B();
supoa.i = 3 ;
supoa.j = 2 ;
System.out.println( " centens of supoa: " );
supoa.showij();
System.out.println();
supob.i = 7 ;
supob.j = 8 ;
supob.k = 10 ;
System.out.println( " centens of supob: " );
supob.showij();
supob.showk();
System.out.println();
System.out.println( " sum of i ,j and k in supob: " );
supob.sum();
}
}
上面代码的运行结果:
centens of supoa:
i and j:5
centens of supob:
i and j:15
k :10
sum of i ,j and k in supob:
i+j+k :25