[Training Video - 3] [Java Introduction] [Object Oriented Programming]

Static and non-Static : 

非静态方法(不带static)可以访问静态变量和方法(带static),但是反过来就不行。

类的静态成员(变量和方法)属于类本身,在类加载的时候就会分配内存,可以通过类名直接去访问

非静态成员(变量和方法)属于类的对象,只有在类的对象产生(创建实例)的时候才会分配内存,然后通过类的对象去访问

在一个类的静态成员中去访问非静态成员之所以会出错是因为在类的非静态成员不存在的时候静态成员就已经存在了,访问一个内存中不存在的东西会出错。

[Training Video - 3] [Java Introduction] [Object Oriented Programming]

静态变量和方法既可以用类来调用,也可以用对象来调用,但不建议用对象调用

Code :

public class Car {

		// GLOBAL VARIABLE
String mod;
int price;
static int wheels = 4; // static functions can only access static stuff
public static void main(String[] args) {
Car c1 = new Car();
c1.mod = "Merc";
c1.price = 8909809;
c1.start();
c1.accel(); Car c2 = new Car();
c2.mod = "Maruti";
c2.price = 8909809;
c2.start();
c2.accel(); System.out.println(c1.mod);
System.out.println(c2.mod); // static
System.out.println(wheels);
System.out.println(Car.wheels); c1.wheels = 8;
System.out.println(wheels);
System.out.println(Car.wheels);
System.out.println(c2.wheels); fillGas(100);
Car.fillGas(200);
c1.fillGas(900);
} public void start(){
System.out.println(mod + " starting");
} public void accel(){
System.out.println(mod + " acc");
} public static void fillGas(int quantity){ }
}

Result :

Merc starting
Merc acc
Maruti starting
Maruti acc
Merc
Maruti
4
4
8
8
8

Code :

public class Car {

		String mod;

		public static void main(String[] args) {
Car a = new Car();
Car b = new Car();
Car c = new Car(); a.mod = "A";
b.mod = "B";
c.mod = "C"; System.out.println(a.mod);
System.out.println(b.mod);
System.out.println(c.mod); a=b;
b=c;
c=a; System.out.println(a.mod);
System.out.println(b.mod);
System.out.println(c.mod);
}
}

Result :

A
B
C
B
C
B
上一篇:人活系列Streetlights (秩)


下一篇:android95 缩放加载大图片