小白教程

 找回密码
 立即注册
小白教程 首页 系列教程 Java系列教程 查看内容

Java 继承

发布者: 小白教程



instanceof 关键字

可以使用 instanceof 运算符来检验 Mammal 和 dog 对象是否是 Animal 类的一个实例。

  1. interface Animal{}
  2. class Mammal implements Animal{}
  3. public class Dog extends Mammal{
  4. public static void main(String args[]){
  5. Mammal m = new Mammal();
  6. Dog d = new Dog();
  7. System.out.println(m instanceof Animal);
  8. System.out.println(d instanceof Mammal);
  9. System.out.println(d instanceof Animal);
  10. }
  11. }

以上实例编译运行结果如下:

  1. true
  2. true
  3. true

HAS-A 关系

HAS-A 代表类和它的成员之间的从属关系。这有助于代码的重用和减少代码的错误。

例子

  1. public class Vehicle{}
  2. public class Speed{}
  3. public class Van extends Vehicle{
  4. private Speed sp;
  5. }

Van 类和 Speed 类是 HAS-A 关系( Van 有一个 Speed ),这样就不用将 Speed 类的全部代码粘贴到 Van 类中了,并且 Speed 类也可以重复利用于多个应用程序。

在面向对象特性中,用户不必担心类的内部怎样实现。

Van 类将实现的细节对用户隐藏起来,因此,用户只需要知道怎样调用 Van 类来完成某一功能,而不必知道 Van 类是自己来做还是调用其他类来做这些工作。

Java 只支持单继承,也就是说,一个类不能继承多个类。

下面的做法是不合法的:

  1. public class extends Animal, Mammal{}

Java 只支持单继承(继承基本类和抽象类),但是我们可以用接口来实现(多继承接口来实现),代码结构如下:

  1. public class Apple extends Fruit implements Fruit1, Fruit2{}

一般我们继承基本类和抽象类用 extends 关键字,实现接口类的继承用 implements 关键字。

123

Archiver|手机版|小黑屋|小白教程 ( 粤ICP备20019910号 )

GMT+8, 2024-9-20 09:00 , Processed in 0.168920 second(s), 30 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc. Template By 【未来科技】【 www.wekei.cn 】

返回顶部