java===java基础学习(9)---方法参数

方法参数注意三要点:

一个方法不能修改一个基本数据类型的参数(数值型或者布尔型)。

一个方法可以改变一个对象参数的状态。

一个方法不能让对象参数引用一个新的对象。

package testbotoo;

public class ParamTest{

    public static void main(String[] args)
{
/*
* Test 1 :Methods cant't modify numeric parameers
*/
System.out.println("Testing tripleValue");
double percent = 10;
System.out.println("before:percent="+percent);
tripleValue(percent);
System.out.println("after:perent="+percent); /*
* Test2 :Methods can change the state of object parameters
*/
System.out.println("\nTesting tripleSalary:");
Empl harry = new Empl("harry", 5000);
System.out.println("\n before salary = "+ harry.getSalary());
tripleSalary(harry);
System.out.println("after salary = "+ harry.getSalary()); /*
* Test 3 : nethods can't attach new objects to objects parameters
*/ System.out.println("\ntesting swap:");
Empl a = new Empl("sss",500);
Empl b = new Empl("bob", 600);
System.out.println("befoer: a = "+ a.getName());
System.out.println("befoer: 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)//dosen't work
{
x = 3*x;
System.out.println("x="+x);
} public static void tripleSalary(Empl x) //works
{
x.raiseSalary(200);
System.out.println("end of method : salary = "+ x.getSalary()); } public static void swap(Empl x ,Empl y)
{
Empl temp = x;
x = y ;
y = temp;
System.out.println("x = "+ x.getName());
System.out.println("y = "+ y.getName());
} } class Empl
{ private String name;
private double salary; public Empl(String n, double s)
{
name = n;
salary = s;
} public String getName()
{ return name;
} public double getSalary()
{
return salary;
} public void raiseSalary(double byPrecent)
{
double raise = salary * byPrecent /100;
salary += raise;
}
}
上一篇:JS中call、apply、bind使用指南,带部分原理。


下一篇:js中call、apply、bind那些事2