展会信息港展会大全

android开发之静态变量与静态函数的应用
来源:互联网   发布日期:2016-01-19 12:41:20   浏览:1697次  

导读:public class Stuff { public static String name = I 39;m a static variable;}public class Application { public static void main(String[] args) { System out println ...

public class Stuff {

public static String name = "I'm a static variable";

}

public class Application {

public static void main(String[] args) {

System.out.println(Stuff.name);

}

}

1.用你静态变量声明常量(在以后过不希望改变的值),用到**final**

public class Stuff {

public final static String NAME = "I'm a static variable";

}

public class Application {

public static void main(String[] args) {

System.out.println(Stuff.NAME);

}

}

2.用静态变量来记录对象(在一个对象里有多少对象被创建了)

首先来回顾一下构造函数:

1. 构造函数名和类名相同

2. 应该声明为public,使外部类可以访问到它

public class Stuff {

public Stuff() {

System.out.println("Stuff object constructed!");

}

}

public class Application {

public static void main(String[] args) {

Stuff stuff1 = new Stuff();

Stuff stuff2 = new Stuff();

Stuff stuff3 = new Stuff();

}

}

构造函数将被自动调用三次

public class Stuff {

// Set count to zero initially.

static int count = 0;

public Stuff() {

// Every time the constructor runs, increment count.

count = count + 1;

// Display count.

System.out.println("Created object number: " + count);

}

}

1. 给对象加ID

public class Stuff {

// Set count to zero initially.

static int count = 0;

// Use this to store an ID for each object.

int id;

public Stuff() {

// Every time the constructor runs, increment count.

count = count + 1;

// Set the object ID using count.

id = count;

// Now count can change but id will be unaffected.

}

// This just returns the ID.

public int getId() {

return id;

}

}

public class Application {

public static void main(String[] args) {

Stuff stuff1 = new Stuff();

Stuff stuff2 = new Stuff();

Stuff stuff3 = new Stuff();

System.out.println("ID of object 2 is: " + stuff2.getId());

}

结果:ID of object 2 is: 2

静态函数不需要实例化

java的Math class的所有成员都是静态的。

赞助本站

人工智能实验室
AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港