[Day21] CH11:刘姥姥逛物件导向的世界——类别与物件

今天开始,我们要进入物件导向的世界了,先前已经简单提过了,物件导向程序设计是一种以物件观念来设计程序的程序设计技巧,透过物件的方法产生互动以完成程序要求。在开始前,先来介绍一些名词解释:

物件(Object)

真实世界中所有具体或抽象的事物,都可以将之视为一个「物件」。例如:橡皮擦、眼镜、脚踏车等等。

类别(Class)

类别里定义了属性(Property)与方法(Method),一个类别当中可以有很多物件,他们都具有同样的属性与方法。属性就像是一个事物拥有的特性,而方法则是事物可以用来操作的动作。例如:定义一个汽车类别,他们有不同的颜色、品牌,且都可以前进和後退,颜色、品牌就是他们的属性,而前进、後退就是他们的方法。

透过范例来看更清楚:

public class MyPokemon{
    public static void main(String[] args){
        Pokemon p1 = new Pokemon();
        p1.setName("Pikachu");
        p1.setAttack(24);
        Pokemon p2 = new Pokemon();
        p2.setName("Squirtle");
        p2.setAttack(18);
        System.out.println("I'm " + p1.getName() + ". I can attack " + p1.getAttack());
        System.out.println("I'm " + p2.getName() + ". I can attack " + p2.getAttack());
    }
}

class Pokemon{
    private String name;
    private int attack;
    public String getName(){
        return name;
    }
    public int getAttack(){
        return attack;
    }
    public void setName(String name){
        this.name = name;
    }
    public void setAttack(int attack){
        this.attack = attack;
    }
}

如范例,只要建立一个神奇宝贝(物件)後,每次都需要输入属性,那如果今天我有 100 只神奇宝贝,不就很麻烦吗?因此可以在类别里使用建构子(constructor),就可以一次赋予所有属性。

前面在介绍方法得时候有提到「多载」,在建构子这里也同样适用。

public class MyPokemon2{
    public static void main(String[] args){
        Pokemon2 p1 = new Pokemon2("Pikachu", 24);
        Pokemon2 p2 = new Pokemon2("Squirtle", 18);
        System.out.println("I'm " + p1.getName() + ". I can attack " + p1.getAttack());
        System.out.println("I'm " + p2.getName() + ". I can attack " + p2.getAttack());
    }
}

class Pokemon2{
    private String name;
    private int attack;

    //定义建构子
    public Pokemon2(String name, int attack){
        this.name = name;
        this.attack = attack;
    }
    public String getName(){
        return name;
    }
    public int getAttack(){
        return attack;
    }
}

两个范例中我们都可以看到有使用 this,每个物件都可以利用关键字 this,来存取指向自己的参照。以上述范例来看,若我们将 setName() 的参数改命名为 n,则我们就不需要 this 来告诉 Java name 是指哪一个,但若是两者皆命名为 name,便需要 this.name 指向自己。

class Pokemon{
    private String name;
    private int attack;
    public String getName(){
        return name;
    }
    public int getAttack(){
        return attack;
    }
    public void setName(String n){
        name = n;
    }
    public void setAttack(int a){
        attack = a;
    }
}

明天我们会介绍为什麽物件导向程序设计的特性,为什麽会适合用来开发、管理大型程序,看似有点抽象,但理解後就不会那麽觉得了!


<<:  Day-06 Classification

>>:  [ Day 06 ] Function Component

Day26,Kubecost 体验,算钱好难......

正文 kubectl create ns kubecost wget https://raw.git...

[Day18]非相关子查询实作

在OE中的order_items和product_information资料表中,查询产品单价>...

近似最短路径 (9)

11.9 赋距空间与 L1 嵌入的 Bourgain 定理 图上的距离也满足赋距空间(metric ...

Day_22 OpenVPN

前几天所述让我们能够连线回所架设的openwrt方法,虽然方便快速但比较粗糙,可以看到我连https...

初学者跪着学JavaScript Day12 : 麻烦的JS加法

一日客语:中文:吃什麽 客语:(ㄘ1声)骂诶 想不到吧~加法可以写一篇,不要怀疑就是要拖台钱(喂~)...