日期:2014-05-20 浏览次数:20749 次
class Person { private String name; private int age; Person(){ System.out.println("this is a void Person()"); } Person(String name,int age){ this.name = name; this.age = age; } public String info(){ return "the man is name:"+name+" age:"+age; } } class Teacher extends Person { private String title; Teacher(){ System.out.println("teacher()"); } Teacher(String name,int age,String title){ super(name,age); this.title = title; } public String info(){ return super.info()+" title:"+title; } public String toString(){ return "i`am a teacher wang!"; } } public class Testequals { public static void main(String arg[]){ Teacher teach1 = new Teacher("wang",45,"high"); Teacher teach2 = new Teacher("wang",45,"high"); System.out.println(teach1.info()); System.out.println(teach1.toString()); System.out.println(teach1.equals(teach2)); } }
class Student { private String name; private String sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } } public class TestStudent{ public static void main(String[] args){ Student student=new Student(); student.setName("zhangsan"); student.setSex("male");
class Student { private String name; private String sex; public Student(){ } public Student(String name ,String sex){ this.name=name; //在同一个类 ,等同this.setName(name); this.sex = sex; //在同一个类 ,this.setSex(sex); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } } public class TestStudent{ public static void main(String[] args){ Student student=new Student(); // student.name="abc" 这一行会编译出错 // 在Student类体之外,要想给name属性赋值 //必须要用public的setter方法,因为name属性声明为private类型 //这就是setter的意义 student.setName("zhangsan"); student.setSex("male"); } }
------解决方案--------------------
什么时候要用就看你自己了,没有发现你的第一个代码中有直接修改变量的,有的只是通过构造的时候赋值的
可以参考下面的代码
public class Person { private String name; private char sex; private int age; public Person() { } public Person(String name, char sex, int age) { this.name = name; this.sex = sex; this.age = age; } public void setName(String name) { this.name = name; } public String getName() { return this.name; } public void setSex(char sex) { this.sex = sex; } public char getSex() { return this.sex; } public void setAge(int age) { this.age = age; } public int getAge() { return this.age; } public void print() { System.out.println("name: " + name + "\n" + "sex: " + sex + "\n" + "age: " + age); } }