*变量分 基本类型 和 引用型。
public class MyDate {
private int day;
private int month;
private int year;
public MyDate(int y, int m, int d) {
year = y;
month = m;
day = d;
}
void addYear(){
year ++;
}
public void display() {
System.out.println(year + "-" + month + "-" +day);
}
public static void main(String[] args) {
MyDate m = new MyDate(2020, 7, 16);
MyDate n = m;
n.addYear();
m.display();
n.display();
}
}
当调试时显示的都是2021,因为引用的是同一个对象
(2)变量又分字段变量和局部变量
*字段变量为对象的一部分,存在于堆中,局部变量存在于栈中
字段变量可以自动赋初值,局部变量则必须显示赋值
(3)变量的传递
Java是值传递,也就是将表达式的值复制给形式参数。
而引用型变量,传递的值是引用值,不是复制对象实体
int a = 0;
modify (a); System.out.println(a);//显示结果t:0
modify(b);
System.out.println(b[0]); //显示结果t:1
}
a++;
}
public static void modify (int[] b) {
b[0] ++;
b = new int[5];
}
}
{
static void doStuff( Shape s ){
s.draw();
}
Circle c = new Circle();
Triangle t = new Triangle();
Line l = new Line();
doStuff(c);
doStuff(t);
doStuff(l);
}
}
class Shape
{
void draw(){ System.out.println("Shape Drawing"); }
}
class Circle extends Shape
{
void draw(){ System.out.println("Draw Circle"); }
}
{
void draw(){ System.out.println("Draw Three Lines"); }
}
{
void draw(){ System.out.println("Draw Line"); }
}
{
static void doStuff( Shape s ){
s.draw();
}
public static void main( String [] args ){
Circle c = new Circle();
Triangle t = new Triangle();
Line l = new Line();
doStuff(c);
doStuff(t);
doStuff(l);
Shape s = new Circle();
doStuff(s);
s.draw();
Circle c2 = new Circle();
c2.draw();
}
}
class Shape
{
static void draw(){ System.out.println("Shape Drawing"); }
}
class Circle extends Shape
{
static void draw(){ System.out.println("Draw Circle"); }
}
{
static void draw(){ System.out.println("Draw Three Lines"); }
}
{
static void draw(){ System.out.println("Draw Line"); }
}