学java的第二天:
首先是
JAVA的传值传址:
**JAVA只有传值。**
大概记住JAVA的变量和基础类型都在栈中,而对象本体在堆中。所以普通变量进入函数,函数自然只改变副本的值(这点和cpp一样),但如果是指向对象的一个变量进入,情况就有所不同了:
如:
Employee a = new Employee(...)
public void DoubleSalary(Emloyee a1)
{
a1.raiseSalary(); //假如说Emloyee类中写了这个函数
}
其中 等号右边是对象本体,然后创建了一个叫a的变量名来指向它。如果a进入函数,则创建了一个副本a1,这个a1也指向对象本身。
工资翻倍这个函数修改了形参 a1 的salary翻倍,意味着对象 a1 的 salary翻倍了,而实参 a 指向的也是对象 a,所以 a 的 salary 也翻倍了。
具体参考:
https://www.zhihu.com/question/385114001
对象构造问题:
主要和cpp有几个点不一样,比如说可以用一个构造函数调用另一个构造函数。 还有初始化块这个东西。
详见以下例子:
public class Sample {
public static void main(String[] args) {
Employee[] staffs = new Employee[3];
staffs[0] = new Employee("harry",1000);
staffs[1] = new Employee(60000);
staffs[2] = new Employee();
for(Employee e : staffs)
System.out.println(e.getName() + "has salary of " + e.getSalary() + "his ID is " + e.getId());
}
}
class Employee
{
private static int nextID;
private String name = "";
private double salary;
private int id;
//静态域初始化代码块 区别于cpp
static
{
Random startnum = new Random();
nextID = startnum.nextInt(10000);
}
//对象初始化代码块(initialization block) 区别于cpp
{
id = nextID;
++nextID;
}
//重载三次构造函数
public Employee(String n,double s)
{
name = n;
salary = s;
}
public Employee(double s) //构造函数调用另一个构造函数 区别于cpp
{
this("Emloyee #" + nextID,s); //调用Employee(String ,double)
}
public Employee()
{
//name set to ""
//salary set to 0
//id已经在initial block 被设置过了
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public int getId()
{
return id;
}
public void setId()
{
id = nextID;
++nextID;
}
public static int getNextID()
{
return nextID;
}
}