2011年12月24日星期六

7天第3节: this关键字、对象比较

===example 4 : adding child
class Person
{
    private String name;
    private int age;
    private Book book;
    private Person child;
    public Person(String n, int a) {
        name = n;
        age  = a;
    }
    public void setBook(Book b) {
        book = b;
    }
    public Book getBook(){
        return book;
    }
    public String getName() {
        return name;
    }
    public void setChild(Person p) {
        child = p;
    }
    public Person getChild() {
        return child;
    }

}
class Book
{
    private String title;
    private float price;
    private Person person;
    public Book (String t, float p) {
        title =t ;
        price =p ;
    }
    public void setPerson(Person p)
    {
        person = p;
    }
    public String getTitle(){
        return title;
    }
    public Person getPerson() {
        return person;
    }   
}
public class testb
{
    public static void main ( String args[] ) {
        Person per = new Person("linfa",30);
        Person chd = new Person("son",5);
        Book bk = new Book("java", 33.0f);
        Book cbk = new Book("story",10.0f);
        per.setBook(bk);
        bk.setPerson(per);
        chd.setBook(cbk);
        per.setChild(chd);
        System.out.println(per.getBook().getTitle());
        System.out.println(bk.getPerson().getName());
        System.out.println(per.getChild().getBook().getTitle());
    }
}


===this ***
1. adding this when referring to properties and method of current class
    private String name;
    private int age;
    public Person(String name, int age) {
        this.name = name;
        this.age  = age;
    }
    public String getName() {
        return this.name;
    }
2. this() can only be put at the first line of constructor
class Person
{
    private String name;
    private int age;
    public Person(){
        System.out.println("creating new obj");
    }
    public Person(String name, int age) {
        this();
        this.name = name;
        this.age  = age;
    }
    public String getName() {
        return name;
    }
}
3. this represent current object ( the address of current obj), this also explains 1)
used for comparison

class Person
{
    private int age;

    public Person(int age) {
        this.age = age;
    }
    public int getAge() {
        return this.age;
    }
    public boolean compare(Person per) {
        if( this == per ) {return true;}
        return (this.age==per.age);
    }
}

public class testb
{
    public static void main ( String args[] ) {
        Person per1 = new Person(30);
        Person per2 = new Person(20);
        if(per1.compare(per2)){
            System.out.println("is the same person");
        }else{
            System.out.println("is not the same person");
        }

    }
}

没有评论: