4.3 实验练习

来源:互联网 发布:mysql 全文检索 中文 编辑:程序博客网 时间:2024/05/29 02:37

4.3.1 实例成员和类成员

class A{float a;static float b;void setA(float a1){a=a1;}void setB(float b1){b=b1;}float getA(){return a;}float getB(){return b;}void inputA(){System.out.println(a);}static void inputB(){System.out.println(b);}}public class Ex4_3{public static void main(String args[]){A.b=100;A.inputB();A cat=new A();A dog=new A();cat.setA(180);cat.setB(380);cat.inputA();cat.inputB();dog.setA(300);dog.setB(800);dog.inputA();dog.inputB();}}


一下是错误的结果与正确的结果。错误的原因是:参数与成员变量都是同一个字母a.

 

4.3.2   公司和职员

class Employee{int age;void setAge(int m){age=m;}void showAge(){System.out.println("年龄:"+age);}}class Corp{Employee secretary;void setSecretary(Employee emp){secretary=emp;}void showSecretaryAge(){secretary.showAge();}}public class Mainclass{public static void main(String args[]){Employee zhangLin=new Employee();zhangLin.setAge(21);Corp tomCorp=new Corp();tomCorp.setSecretary(zhangLin);System.out.println("tomCorp公司的秘书年龄:");tomCorp.showSecretaryAge();zhangLin.setAge(22);Employee jiangHua=new Employee();jiangHua.setAge(28);tomCorp.setSecretary(jiangHua);System.out.printf("zhangLin(年龄:%d)不再是公司的秘书了\n",zhangLin.age);System.out.println("tomCorp公司的秘书年龄:");tomCorp.showSecretaryAge();}}


原创粉丝点击