首页 > 其他 > 详细

CS2312 Lecture 5

时间:2018-02-24 00:37:04      阅读:319      评论:0      收藏:0      [点我收藏+]

Inheritance and Scope

Inheritance:
Objects that are derived from other object "resemble" their parents by inheriting both state (fields) and behaviour (methods).
Parents are more general than children
Children refine parents class specification for different uses
 
Inheritance allows to write new classes that inherit from existing classes
The existing class whose properties are inherited is called the "parent" or superclass
The new class that inherits from the super class is called the "child" or subclass
Result: Lots of code reuse!

技术分享图片

技术分享图片
package test;

public class Animal {
    public int numOfLegs;

    public Animal(int numOfLegs){
        this.numOfLegs = numOfLegs;
    }

    public int getNumOfLegs(){
        return this.numOfLegs;
    }


    public static void main(String args[]){
        Dog xiaogou = new Dog();
        Duck xiaoya = new Duck();

        System.out.println("A dog has "+xiaogou.getNumOfLegs()+" and "+xiaogou.bark());   //A dog has 4 and Woof
        System.out.println("A duck has "+xiaoya.getNumOfLegs()+" and "+xiaoya.bark());   //A duck has 2 and Quack
        // Dog and Duck inherit the getNumLegs() method from the Animal super class,
        // but get bark and quack from their own class.
    }
}
Animal
技术分享图片
package test;

public class Duck extends Animal{
    public Duck(){
        super(2);
    }
    public String bark(){
        return "Quack";
    }
}
Duck
技术分享图片
package test;

public class Dog extends Animal{
    public Dog(){
        super(4);
    }
    public String bark(){
        return "Woof";
    }
}
Dog
Use the extends keyword to indicate that one class inherits from another
The subclass inherits all the fields and methods of the superclass
Use the super keyword in the subclass constructor to call the superclass constructor

 

Inheritance defines an “is-a” relationship
  • Dog is an Animal
  • Duck is an Animal
One way relationship
  • Animal is not a Dog!  (Remember this when coding!)
The derived class inherits access to methods and fields from the parent class
  • Use inheritance when you want to reuse code
When one class has a field of another class (or primitive type) - “has-a” relationship
  • Animal has an int

 

CS2312 Lecture 5

原文:https://www.cnblogs.com/charon922/p/8463779.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!