类和对象的属性:



下面例子中,zhang和li这两个是两个实例或叫对象,这两个是一类,什么类?是Student这一类,不是'花'这一类。int和string都是单一类型的,有时不够用。比如我想记录zhang98分,li95分,这件事就很困难,所以我用“类”这个复杂数据来记录。

int b;像一个抽屉叫b,里面没有东西就是0。
int a=5;另一个抽屉叫a,里面放一个5,
Studen1 zhang = new Student();这句话之后new两个抽屉总称叫zhang,一个叫name,一个叫fenshu,name的抽屉是空的,fenshu抽屉是空的也是0.
zhang.name = "zhangsan";这句话之后才把"zhangsan"放入抽屉里。
zhang.fenshu = 98;这句话之后才把98放入抽屉里。

马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。
name和fenshu是Student类的两个属性。



例1:

class Student {
    String name;
    int fenshu;
}

public class test6 {
    public static void main(String[] args) {
        int a = 5;
        int b;
        Student zhang = new Student();
        zhang.name = "zhangsan";
        zhang.fenshu = 98;
        System.out.println(zhang.name + zhang.fenshu);
        Student li = new Student();
        li.name = "lisi";
        li.fenshu = 95;
        System.out.println(li.name + li.fenshu);
    }
}

结果:
zhangsan 98
lisi 95


例2:

class Tv {
    String name;
    int jiage;
}
public class test1 {
    public static void main(String[] args) {
        int a = 0;
        Tv fei = new Tv();
        a = 2;
        fei.name = "feilipu";
        fei.jiage = 2000;
        System.out.println(a+fei.name + fei.jiage);
        int b = 0;
        Tv chuang = new Tv();
        b = 3;
        chuang.name = "chuagnwei";
        chuang.jiage = 3000;
        System.out.println(b+chuang.name + chuang.jiage);
    }
}
结果:
2feilipu 2000
3chuagnwei 3000




 
作业1:马克-to-win:编一个类名字叫车,一个属性叫名字,一个属性叫价格

class Car {
    String name;
    int jiage;
}
public class test2 {
    public static void main(String[] args) {
        int a = 0;
        Car ao = new Car();
        a = 2;
        ao.name = "aodi";
        ao.jiage = 500000;
        System.out.println(ao.name + ao.jiage);
        int b = 0;
        Car da = new Car();
        b = 3;
        da.name = "daben";
        da.jiage = 800000;
        System.out.println(da.name + da.jiage);
    }
}
结果:
aodi 500000
daben8 00000

作业2:马克-to-win:马克java社区:编一个类名字叫水果,一个属性叫颜色,一个属性叫价格

class Shuiguo {
    String yanse;
    int jiage;
}
public class test3 {
    public static void main(String[] args) {
        int a = 0;
        Shuiguo haugn = new Shuiguo();
        a = 2;
        haugn.yanse = "huangse";
        haugn.jiage = 5;
        System.out.println(haugn.yanse + haugn.jiage);
        int b = 0;
        Shuiguo hong = new Shuiguo();
        b = 3;
        hong.yanse = "hongse";
        hong.jiage = 8;
        System.out.println(hong.yanse + hong.jiage);
    }
}
结果:
huangse 5
hongse 8