看注释:
class Person2 { String name; int score; String phone;}class App { public static void main(String[] args) { int size = 20; Person p1 = new Person(); Person p2 = new Person(); /* Person p3 = p1; p2 = p3; 这三个p1,p2,p3,都只是一个引用类型,只存在两个new出来的对象,而第14行p2指向了第一个引用的 对象后,第二个对象唯一的“线”就“断”了,有Java中的GC(垃圾回收机制)标记,当内存分配给其他不够时 这款内存就会比用掉。比喻:对象为两个空调,而这三个引用类型相当于三个遥控器,连着这两个对象,进行操作。 */ /*对象必须要有引用,一旦没有引用指向,在特定是条件和时机后,就会被...*/ p1.name = "Alice"; p1.score = 98; p1.phone = "12131"; p2.name = "Bob"; p2.score = 95; p2.phone = "12134"; Person tmp; tmp = p1; tmp.score = 100; System.out.println(p1.score);//打印100 /*在这里tmp和p1指向的都是一个对象,所以改变tmp的数据对象的值,p1的也同样变了 */ }}
class Person { String name; int score; String phone; void display() { System.out.printf("name=%s\tscore=%d\tphone=%s\n",name,score,phone); }}class App3 { public static void main(String[] args) { int size = 20; Person p1 = new Person(); Person p2 = new Person(); p1.name = "Alice"; p1.score = 98; p1.phone = "12131"; p2.name = "Bob"; p2.score = 95; p2.phone = "12134"; Person[] ps = new Person[3]; p1 = new Person(); p1.name = "Alice"; p1.score = 98; p1.phone = "12131"; ps[0] = p2; ps[1] = p1; ps[2] = new Person(); ps[2].name = "Jack"; ps[2].score = 90; ps[2].phone = "33231"; // ps[1] = new Person();//如果又new了一个,则ps[1]指向的是新的空的才分配出来的一个对象 for(Person person : ps) person.display(); System.out.println(); for(int i = 0; i < ps.length; i++) { Person p = ps[i]; p.display(); } for(int j = 0; j
class Person { String name; int score; String phone; void display() { System.out.printf("name=%s\tscore=%d\tphone=%s\n",name,score,phone); } String sayHello(String msg) { return "你好,"+msg+",我是"+name; }}class App2 { public static void main(String[] args) { int size = 20; Person p1 = new Person(); Person p2 = new Person(); p1.name = "Alice"; p1.score = 98; p1.phone = "12131"; p2.name = "Bob"; p2.score = 95; p2.phone = "12134"; p1.display(); p2.display(); System.out.println(p1.sayHello("2017")); //交换演示// Person tmp; tmp = p1; p1 = p2; p2 = tmp; p1.display(); p2.display(); }}
import java.util.Scanner;class Book { String bookName; int price; String writer; //书名 //价格 //作者 void display() { System.out.printf("书名:%s\t价格:%d\t作者:%s\n",bookName,price,writer); }}class BookManage { static void Bsort(Book[] book ) { for(int j = 0; j < book.length-1; j++){ for(int i = 0; i < book.length-1; i++) { if(book[i].price>book[i+1].price) { Book tmp = book[i]; book[i] = book[i+1]; book[i+1] = tmp; } } }} public static void main(String[] args) { int number = 5; Scanner cin = new Scanner(System.in); Book[] book = new Book[number]; for(int i = 0; i