java方法参数详析

  1. 方法参数介绍
  2. java中参数的…

方法参数介绍

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

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

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

事实上,java各种参数传递都是值传递(一种拷贝的传递),而不是引用,详见核心技术卷一 P123。辅助理解代码如下:

public class Test
{
    public static void main(String args[])
    {
        System.out.println("Testing1:");
        double percent = 10;
        System.out.println("before pecent=" + percent);    
        tripleValue(percent);
        System.out.println("after pecent=" + percent);

        System.out.println("Testing2:");
        Employee Herry = new Employee("Herry", 70000);
        System.out.println("before: salary=" + Herry.getSalary());
        tripleSalary(Herry);
        System.out.println("after: salary=" + Herry.getSalary());

        System.out.println("Testing3:");
        Employee a = new Employee("Alice", 70000);
        Employee b = new Employee("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;
        System.out.println("end of method: x=" + x);
    }

    public static void tripleSalary(Employee x)
    {
        x.raiseSalary(200);
        System.out.println("end of method: salary=" + x.getSalary());
    }

    public static void swap(Employee x, Employee y)
    {
        Employee temp = x;
        x = y;
        y = temp;
    }
}

class Employee
{
    private String name;
    private double salary;

    public Employee(String n, double s)
    {
        name = n;
        salary = s;
    }

    public String getName()
    {
        return name;
    }
    public double getSalary()
    {
        return salary;
    }
    public void raiseSalary(double percent)
    {
        salary *= (1 + percent/100);
    }
}

output:

Testing1:
before pecent=10.0
end of method: x=30.0
after pecent=10.0 //没变
Testing2:
before: salary=70000.0
end of method: salary=210000.0
after: salary=210000.0 //变了
Testing3:
before: a=Alice
before: b=Bob
after: a=Alice
after: b=Bob //没变

java中参数的…

…表示的是可变长参数,相当于一个数组

如果是是形参 里面出现,表示的是可变参数
比如:
//表示的传入的参数可以随意,你传多少个参数都被放到一个数组里面。
public static void dealArray(int...intArray) {
for(int i: intArray)
{
System.out.print(i +" ");
}
System.out.println();
}

欢迎转载,欢迎错误指正与技术交流,欢迎交友谈心

文章标题:java方法参数详析

文章字数:473

本文作者:Brain Cao

发布时间:2017-06-26, 10:53:26

最后更新:2020-03-15, 16:23:54

原始链接:https://braincao.cn/2017/06/26/java-parameter/

版权声明:本文为博主原创文章,遵循 BY-NC-SA 4.0 版权协议,转载请保留原文链接与作者。

目录
×

喜欢请收藏,疼爱就打赏