现在的位置: 首页 > 综合 > 正文

Java基础学习之(二)—对象与类的方法参数

2013年10月05日 ⁄ 综合 ⁄ 共 2155字 ⁄ 字号 评论关闭

一、Java中,方法参数的使用情况:

1、一个方法不能修改一个基本数据类型的参数;

2、一个方法可以改变一个对象参数的状态;

3、一个方法不能让对象参数引用一个新的对象;

例子代码为:

package com.study.write;

public class ParamTest {
	public static void main(String[] args) {
		/*方法不能修改基本数据类型参数*/
		System.out.println("Testing tripleValue");
		double percent = 10;
		System.out.println("Before:percent=" + percent);
		tripleValue(percent);
		System.out.println("After:percent=" + percent);
		
		/*方法能改变对象参数的状态*/
		System.out.println("/nTesting tripleSalary:");
		Employee1 harry = new Employee1("Harry", 50000);
		System.out.println("Before:salary=" + harry.getSalary());
		tripleSalary(harry);
		System.out.println("After:salary=" + harry.getSalary());
		
		/*方法不能让对象参数引用一个新的对象*/
		System.out.println("/nTesting swap:");
		Employee1 a = new Employee1("Alice", 70000);
		Employee1 b = new Employee1("Bob", 60000);
		System.out.println("Before: a=" + a.getName());
		System.out.println("Before: b =" + b.getName());
		swap(a, b);
		System.out.println("After: a=" + a.getName());
		System.out.println("After: b=" + b.getName());
	}
	
	public static void tripleValue(double x) {
		x = 3*x;
		System.out.println("End of method: x=" + x);
	}
	
	public static void tripleSalary(Employee1 x) {
		x.raiseSalary(200);
		System.out.println("End of method:salary=" + x.getSalary());
	}
	
	public static void swap(Employee1 x, Employee1 y) {
		Employee1 temp = x;
		x = y;
		y = temp;
		System.out.println("End of method: x=" + x.getName());
		System.out.println("End of method: y=" + y.getName());
	}

}

class Employee1 {
	public Employee1(String n, double s) {
		name = n;
		salary = s;
	}
	
	public String getName() {
		return name;
	}
	
	public double getSalary() {
		return salary;
	}
	
	public void raiseSalary(double byPercent) {
		double raise = salary * byPercent;
		salary += raise;
	}
	
	private String name;
	private double salary;
}

二、final关键字

private final Date hiredate;

存储在hiredate变量中的对象引用在对象构造之后不能被改变。而并不意味着hiredate对象是一个常量。任何方法都可以对hiredate引用的对象调用setTime更改器。

例子代码:

package com.study.write;


public class TestFinal {
	
	public static void main(String[] args) {
		Date d = new Date(2012, 3, 14);
		final Date hiredate = d;
		System.out.println(hiredate.toString());
		d.setDate(2012, 3, 15);
		System.out.println(hiredate.toString());
	}

}

class Date {
	public Date(int y, int m, int d) {
		year = y;
		month = m;
		day = d;
	}
	
	public String toString() {
		return String.valueOf(year) + String.valueOf(month) + String.valueOf(day);
	}
	
	public void setDate(int yy, int mm, int dd) {
		year = yy;
		month = mm;
		day = dd;
	}
	private int year;
	private int month;
	private int day;
}

结果:

抱歉!评论已关闭.