7

java面向对象三大特征

 3 years ago
source link: http://www.cnblogs.com/tyy8/p/14353288.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

java面向对象三大特征

封装

利用抽象数据类型将数据和基于数据的操作封装在一起,数据被保护在抽象数据类型的内部,经可能隐藏内部的细节,只保留一些对外的的接口,用户无需知道对象内部的细节,但是可以通过对象对外提供的接口来访问该对象

以下Person类封装的name,gender,age等属性,外界只能通过get()方法获取一个Person对象的name属性和gender属性,而无法获取age属性,但是age属性可以可以供work()方法使用

注意gender属性使用int数据类型进行存储,封装使得用户注意不到这种实现细节,并且在需要修改gender属性

使用数据类型的时候时,也可以在不影响客户端代码的情况下进行

class Person1{
    private  String name;
    private int gender;
    private int age;

    public Person1(String name, int gender, int age) {
        this.name = name;
        this.gender = gender;
        this.age = age;
    }

   


    public String getName(){
        return name;
    }

    public String getGender(){
        return gender == 0?"man":"woman";
    }

    public void work(){
        if(19 <= age && age<=50){
            System.out.println(name+"is working very hard");
        }else{
            System.out.println(name+"can not work any more");
        }
    }
}

继承

继承实现了IS-A关系,例如Cat和Animal就是一种IS-A的关系,因此Cat可以继承自Animal,从而获得Animal非private的属性和方法,

继承因该遵循里氏替换原则,子类对象必须能够使用替换所有父类对象

Cat可以当作Animal来使用,也就是说可以使用Animal引用Cat对象,父类引用指向子类对象称之为** 向上转型 **

Animal animal = new Cat();

多态

多态分为编译时多态和运行时多态:

  • 编译时多态主要指方法的重载
  • 运行时多态指程序中定义的对象引用所指向的具体类型在运行期间才确定

运行时多态有三个条件:

  • 继承

  • 重写

  • 向上转型

下面的代码中,乐器类Instrument有两个子类:Wind和Percusssion,他们都重写了父类的play方法,

并且在main()方法中使用父类Instrument来引用Wind和Percussion对象,在Instrument引用调用

play()方法时,会执行实际引用对象所在类的olay()方法,而不是Instrument类的方法

public class Instrument{
    public void play(){
        System.out.println("Instrument is playing");
    }
}

public class Wind extends Instrument{
    public void play(){
        System.out.println("Wind is playing");
    }
}
public class Percussion extends Instrument{
    public void play(){
        System.out.println("Percussion is playing");
    }
}

public class Music{
    public static void main(String[] args){
        List<Instrument> instruments = new ArrayList<>();
        instruments.add(new Wind());
        instruments.add(new Percussion());
        for(Instrument instrument : instruments){
            instrument.play();
        }
    }
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK