疯狂java


您现在的位置: 疯狂软件 >> 新闻资讯 >> 正文

Java引用传递的基本应用


 

   

  package com.cloud.day1;

  public class Demo1 {

  public static void main(String[] args) {

  // 引用传递的基本应用

  Demo2 d2=new Demo2();

  d2.temp=500;

  System.out.println("fun调用前:"+d2.temp);

  fun(d2);

  System.out.println("fun调用后:"+d2.temp);

  System.out.println("**********");

  String str1="hello";

  System.out.println("fun1调用前:"+str1);

  fun1(str1);

  System.out.println("fun1调用后:"+str1);

  System.out.println("**********");

  Demo3 d3=new Demo3();

  d3.temp="world";

  System.out.println("fun1调用前:"+d3.temp);

  fun2(d3);

  System.out.println("fun1调用后:"+d3.temp);

  //接收自己本类的引用

  System.out.println("**********");

  Demo4 d4=new Demo4();

  d4.setTemp(100);

  d4.fun(d4);

  System.out.println(d4.getTemp());

  //案例:一一对应关系

  Person per=new Person("Tom", 20);

  Book bk=new Book("JAVA教程",50.0f);

  per.setBook(bk);

  bk.setPerson(per);

  System.out.println("人找书:"+per.getName()+"--"+per.getBook().getTitle()+"--"+per.getBook().getPrice());

  System.out.println("书找人:"+bk.getTitle()+"--"+bk.getPerson().getName());

  }

  public static void fun(Demo2 d2){

  d2.temp=1000;

  }

  public static void fun1(String str2){

  str2="mdld";

  }

  public static void fun2(Demo3 d3){

  d3.temp="mldl";

  }

  }

  class Demo2{

  int temp=100;

  }

  class Demo3{

  String temp="hello";

  }

  class Demo4{

  private int temp=30;

  public void fun(Demo4 d4){

  d4.temp=40;

  }

  public int getTemp() {

  return temp;

  }

  public void setTemp(int temp) {

  this.temp = temp;

  }

  }

  class Person{

  private String name;

  private int age;

  private Book book;

  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 Book getBook() {

  return book;

  }

  public void setBook(Book book) {

  this.book = book;

  }

  public Person(String name,int age){

  this.setName(name);

  this.setAge(age);

  }

  }

  class Book{

  private String title;

  private float price;

  private Person person;

  public Book(String title,float price){

  this.setTitle(title);

  this.setPrice(price);

  }

  public String getTitle() {

  return title;

  }

  public void setTitle(String title) {

  this.title = title;

  }

  public float getPrice() {

  return price;

  }

  public void setPrice(float price) {

  this.price = price;

  }

  public Person getPerson() {

  return person;

  }

  public void setPerson(Person person) {

  this.person = person;

  }

  }

  最后一个案例很重要,在javaweb三大框架中应用到。