2011年12月24日星期六

7天第2节: 深入引用

==== storagy
class demo
{
    String s = "hello";
    int x=10;
}
demo d = new demo();

d: on stack pointing to heap object dobj
dobj: has two entries: x and s;
x: has value 10;
s: has a pointer to heap object sobj
sobj: has value "hello"



====example 1: output is 100
public class testb
{
    public static void main ( String args[]) {
        intdemo intx = new intdemo();
        intx.x = 30;
        fun(intx);
        System.out.println(intx.x);
    }

    static void fun ( intdemo temp) {
        temp.x = 100;
    }

}

class intdemo
{
    int x = 10;
}

==example 2 : output is "hello" ***
public class testb
{
    public static void main ( String args[]) {
        String s = "hello";
        fun(s);
        System.out.println(s);
    }

    static void fun ( String temp) {
        temp = "world";
    }

}

===example 3: output is world2
public class testb
{
    public static void main ( String args[]) {
        intdemo d = new intdemo();
        d.s = "world";
        fun(d);
        System.out.println(d.s);
    }

    static void fun ( intdemo temp) {
        temp.s = "world2";
    }

}

class intdemo
{
    String s = "hello";
}

===example 4: a person has a book, a book has a person
class Person
{
    private String name;
    private int age;
    private Book book;
    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;
    }

}
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("lin",30);
        Book bk = new Book("java", 33.0f);
        per.setBook(bk);
        bk.setPerson(per);
        System.out.println(per.getBook().getTitle());    //==>java
        System.out.println(bk.getPerson().getName());  //==>lin
    }
}


没有评论: