java结构体:

给大家补充一个结构体的例子:下面TwoNumber就是一个形式上的结构体:


class TwoNumber {
    int num1;
    int num2;
}

public class Test {
    public static void main(String[] args) {
        int a=0;
        TwoNumber A = new TwoNumber();
        a=3;
        A.num1=333;
        A.num2=333;
        System.out.println("A.num1 is "+A.num1);
      
        int b=0;
        TwoNumber B = new TwoNumber();
        b=4;
        B.num1=444; 
        B.num2=444; 
        System.out.println("B.num2 is "+B.num2);
    }
}




结果:

A.num1 is 333
B.num2 is 444
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。
作业:
1)仿照上面的例子,用类class来做一个类似c当中的叫做Window的结构体,两个属性:width和height。之后测试。
2)仿照上面的例子,用类class来做一个类似c当中的叫做Student的结构体,两个属性:name和height。之后测试。

答案:
1)

class Window {
    int width;
    int height;
}

public class Test {
    public static void main(String[] args) {
        int a=0;
        Window baofeng = new Window();
        a=3;
        baofeng.width=333;
        baofeng.height=333;
        System.out.println("baofeng.width is "+baofeng.width);
     
        int b=0;
        Window xunlei = new Window();
        b=4;
        xunlei.width=444;
        xunlei.height=444;
        System.out.println("xunlei.height is "+xunlei.height);
    }
}




结果:
baofeng.width is 333
xunlei.height is 444


2)

class Student {
    String name;
    int height;
}

public class Test {
    public static void main(String[] args) {
        int a=0;
        Student first = new Student();
        a=3;
        first.name="zhangsan";
        first.height=170;
        System.out.println("first.name is "+first.name);
    
        int b=0;
        Student second = new Student();
        b=4;
        second.name="lisi";
        second.height=180;
        System.out.println("second.height is "+second.height);
    }
}

结果:
first.name is zhangsan
second.height is 180