码迷,mamicode.com
首页 > 编程语言 > 详细

Java中的继承

时间:2017-06-03 10:00:27      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:href   关键字   asics   面向对象   adf   代码   私有属性   logs   接下来   

以下内容引用自http://wiki.jikexueyuan.com/project/java/inheritance.html

继承可以被定义为一个对象获取另一个对象属性的过程。使用继承可以使信息以继承顺序有序管理。

当谈论起继承,最常用的关键字应该为extends和implements。这些关键字将决定一个对象是否是A类型或是其他类型。通过使用这些关键字,可以使一个对象获得另一个对象的属性。

一、IS-A关系

IS-A是说:这个对象所属于另一个对象。下面是用关键字extends来实现继承。

public class Animal{
}

public class Mammal extends Animal{
}

public class Reptile extends Animal{
}

public class Dog extends Mammal{
}

现在,基于上面的例子,在面向对象编程中,请遵循以下几点:

  • Animal是Mammal类的父类。
  • Animal是Reptile类的父类。
  • Reptile和Mammal是Animal类的子类。
  • Dog是Mammal类和Animal类的子类。

现在,针对IS-A关系,可以说:

  • Mammal是一个Animal
  • Reptile是一个Animal
  • Dog是一个Mammal
  • Dog也是一个Animal

使用关键字extends,子类可以继承父类除了私有属性的所有属性。

使用instance操作可以保证Mammal实际上是一个Animal。

示例:

class Animal{
}

class Mammal extends Animal{
}

class Reptile extends Animal{
}

public class Dog extends Mammal {
    public static void main(String args[]){
        Animal a = new Animal();
          Mammal m = new Mammal();
          Dog d = new Dog();

          System.out.println(m instanceof Animal);
          System.out.println(d instanceof Mammal);
          System.out.println(d instanceof Animal);
    }
}
//这将得到如下结果:
true
true
true

已经很好理解了extends关键字,接下来看implements关键字是如何确立IS-A关系的。

implements关键字,是在类继承接口的时候使用的。接口是不能被类使用extends继承的

implements还可以继承多个接口。

示例:

public interface Animal {}

public class Mammal implements Animal{
}

public class Dog extends Mammal{
}

二、关键字instanceof

使用instanceof操作符来检查确定是否Mammal,实际上是Animal,dog实际上是一种Animal。

interface Animal{}

class Mammal implements Animal{}

public class Dog extends Mammal{
   public static void main(String args[]){

      Mammal m = new Mammal();
      Dog d = new Dog();

      System.out.println(m instanceof Animal);
      System.out.println(d instanceof Mammal);
      System.out.println(d instanceof Animal);
   }
} 
//这将产生如下结果:
true
true
true

三、HAS-A关系

该关系是基于使用方便的。这决定了一个类是否含有A的一些属性。该关系帮助减少代码重复和漏洞的出现。

看下面的例子:

public class Vehicle{}
public class Speed{}
public class Van extends Vehicle{
    private Speed sp;
} 

这个例子表明Van含有Speed。因为单独定义了Speed类,不必将整个Speed类的代码加入Van类,使其在多个应用程序中重用Speed类。

在面向对象中,用户不用去考虑哪一个对象在做实际的工作。为了实现这个功能, Van类向用户隐藏了实现具体细节的类。当用户让Van类去做一项工作时,Van类或者自己来做,或者求助其他类来做这项工作。

请记住一个非常重要的事实,Java只支持单继承,这意味着一个类只能继承一个类,所以以下的是非法的

public class extends Animal, Mammal{} 

然而,一个类可以实现一个或多个接口,这使得Java可以摆脱不能多继承的问题。

 

测试工程:https://github.com/easonjim/5_java_example/tree/master/javabasicstest/test17

Java中的继承

标签:href   关键字   asics   面向对象   adf   代码   私有属性   logs   接下来   

原文地址:http://www.cnblogs.com/EasonJim/p/6935681.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!