- 直接赋值
public class student { String name; // 不能有private int age; student(){ } // 不可缺少 student(String name,int age){ this.name =name; // 可有可无 this.age = age; } // 无get()set() public void show() { System.out.println("学生爱学习"); } }
- 利用set()赋值,get()接收
public class Teacher { private String name; // private可有可无 private int age; public Teacher(){ } // 必有空参,不可缺少 public Teacher(String name,int age){ this.name = name; // 可有可无 this.age = age; } // 用set赋值 必有get()set() public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void show(){ System.out.println("老师爱讲课"); } }
- 构造函数赋值
public class xiaozhang { private String name; // 可有可无 private int age; public xiaozhang() { } // 必有空参,不可缺少 public xiaozhang(String name, int age) { this.name = name; // 必有this.变量 this.age = age; System.out.println(name); // 若无set()get(),则必有输出sout System.out.println(age); // 若有set get,则test中必有System.out.println(xz.getName()); System.out.println("校长爱转圈"); } } /* public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age;*/
- 测试类test
public class practice { public static void main(String[] args) { // 直接赋值,不能有private student stu = new student(); stu.name = "小明"; stu.age = 15; System.out.println(stu.name); System.out.println(stu.age); stu.show(); // 对象名调用函数 System.out.println("————————"); //用set() get()赋值 Teacher t = new Teacher(); t.setName("李老师"); t.setAge(45); System.out.println(t.getName()); // 用set赋值用get接收 System.out.println(t.getAge()); t.show(); System.out.println("————————"); //用构造函数赋值 xiaozhang xz = new xiaozhang("张校长",60); //System.out.println(xz.getName()); //System.out.println(xz.getAge());
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/292580.html