RSS
热门关键字:
当前位置 : 主页>编程开发>java编程>入门>列表

java 继承的基础

来源:我要研发网 作者: 时间:2008-03-02 点击:



继承是面向对象编程技术的一块基石,因为它允许创建分等级层次的类。运用继承,你能够创建一个通用类,它定义了一系列相关项目的一般特性。该类可以被更具体的类继承,每个具体的类都增加一些自己特有的东西。在Java 术语学中,被继承的类叫超类(superclass ),继承超类的类叫子类(subclass )。因此,子类是超类的一个专门用途的版本,它继承了超类定义的所有实例变量和方法,并且为它自己增添了独特的元素。
继承一个类,只要用extends 关键字把一个类的定义合并到另一个中就可以了。为了理解怎样继承,让我们从简短的程序开始。下面的例子创建了一个超类A和一个名为B的子类。注意怎样用关键字extends 来创建A的一个子类。 字串5

// A simple example of inheritance.

字串2

// Create a superclass.
class A {
int i, j;
字串3

void showij() { System.out.println("i and j: " i " " j); }} 字串2

// Create a subclass by extending class A.
class B extends A {
int k;

字串4

void showk() {

字串9

System.out.println("k: " k); } void sum() { 字串4

System.out.println("i j k: " (i j k));
}
}

字串4

class SimpleInheritance { 字串8

public static void main(String args[]) {
A superOb = new A();
B subOb = new B();

字串6

// The superclass may be used by itself. superOb.i = 10; superOb.j = 20;
System.out.println("Contents of superOb: "); superOb.showij(); System.out.println();

字串1

/* The subclass has Access to all public members of

字串3

its superclass. */ subOb.i = 7; subOb.j = 8; subOb.k = 9; System.out.println("Contents of subOb: "); subOb.showij();subOb.showk(); System.out.println();

字串6

System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}

字串2

该程序的输出如下: 字串7

Contents of superOb:
i and j: 10 20
字串2

Contents of subOb:
i and j: 7 8

字串9

k: 9 字串4

Sum of i, j and k in subOb:
i j k: 24

字串9

像你所看到的,子类B包括它的超类A中的所有成员。这是为什么subOb 可以获取i和j 以及调用showij( ) 方法的原因。同样,sum( ) 内部,i和j可以被直接引用,就像它们是B的一部分。

字串5

尽管A是B的超类,它也是一个完全独立的类。作为一个子类的超类并不意味着超类不能被自己使用。而且,一个子类可以是另一个类的超类。声明一个继承超类的类的通常形式如下: 字串9

class subclass-name extends superclass-name {
// body of class
}

字串4

你只能给你所创建的每个子类定义一个超类。Java 不支持多超类的继承(这与C 不同,在C 中,你可以继承多个基础类)。你可以按照规定创建一个继承的层次。该层次中,一个子类成为另一个子类的超类。然而,没有类可以成为它自己的超类。

字串4

8.1.1 成员的访问和继承
尽管子类包括超类的所有成员,它不能访问超类中被声明成private 的成员。例如,考虑下面简单的类层次结构:

字串8

/* In a class hierarchy, private members remain private to their class. 字串6

This program contains an error and will not
compile.
*/
字串8

// Create a superclass. 字串3

class A {int i; // public by default private int j; // private to A 字串4

void setij(int x, int y) { i = x; j = y;

字串4

}
}

字串6

// A's j is not accessible here. 字串6

class B extends A { int total; void sum() { 字串2

total = i j; // ERROR, j is not accessible here
}
}

字串8

class Access {
public static void main(String args[]) {
B subOb = new B();
字串5

subOb.setij(10, 12);

字串2

subOb.sum();
System.out.println("Total is " subOb.total);
}
}

字串2

该程序不会编译,因为B中sum( ) 方法内部对j的引用是不合法的。既然j被声明成private,它只能被它自己类中的其他成员访问。子类没权访问它。

字串1

注意:一个被定义成private 的类成员为此类私有,它不能被该类外的所有代码访问,包括子类。

字串9

8.1.2 更实际的例子
让我们看一个更实际的例子,该例子有助于阐述继承的作用。这里,前面章节改进的Box类的最后版本将被扩展。它包括第四成员名为weight 。这样,新的类将包含一个盒子的宽度、高度、深度和重量。

最新评论共有 0 位网友发表了评论
发表评论
评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名: 密码:
匿名?
注册
相关文章