类型:转载 责任编辑:asp.net 日期:2007/05/23
热门软件下载:
package ThinkingInJava.Ch2;
class StaticTest {
//static int i=47;
static String sa="asdfasdfasd";
static int storage(String s){
return s.length()*2;
}
public static void main(String[] args) {
int a=storage(sa) ;
System.out.print(a);
}
}
为什么不加static不能调用storage函数?
练习题答案:
//: c02:E05_Storage.java
/****************** Exercise 5 ******************
* Write a program that includes and calls the
* storage() method defined as a code fragment in
* this chapter.
***********************************************/
public class E05_Storage {
String s = "Hello, World!";
int storage(String s) {
return s.length() * 2;
}
void print() {
System.out.println("storage(s) = " + storage(s));
}
public static void main(String[] args) {
E05_Storage st = new E05_Storage();
st.print();
}
} ///:~
网友回答:
main是静态函数, 不用对象就调用的函数也就是静态函数了。
因为如果不是static方法,不能在未实例化类而使用该方法。所以,答案中使用了 E05_Storage st = new E05_Storage(); 来实例化类,生成对象st ,然后st就可以调用类里面的方法了。
如果不是static方法或者属性
那么这些方法和属性是属于定义他们的类的
根据类的定义,访问类的属性和方法必须通过类的实例来调用
即
st=new E05_Storage();
这时可以访问st的属性和方法:
st.s="1234";
st.storage();等
而根据static的感念,定义为static的属性和方法是独立于类的,所以可以直接调用
如:
sa="1234";
storage(sa);
这也就是为什么main方法需要定义为static一样。
在static方法中只能调用static方法。
这里main是static方法,所以storage必须申明为static型的,才能在main中以
StaticTest.storage的形式调用
否则,就得在main中先申明一个StaticTest型对象,然后才能以A.storage的形式调用
如果不是 static ,只是声明了方法,实际物理上还未建立,所以要 new 一次,产生一个对象才能调用。
如果是 static ,就能直接调用了。
所以, 或者 static 时直接调用,或者 无static时 new 一个再用。
正如楼上朋友说的
这就是static的作用
静态的方法只能调用静态的方法和变量,这和类的存储有关系
在类建立时普通的成员是在堆中分配存储空间的,而静态的变量和方法则
是在静态区中分配存储空间的,类中的成员能够知道静态的方法和变量的地址,
所以能够调用静态的方法和变量,但是静态的方法确无法得到类中普通成员的地址,
所以如果调用只能通过对象来调用普通的变量和方法。
同意楼上
static定义的是类成员,可以直接用类名调用,否则就一定要先创建这个类的实例对象才可以
对于类E05_Storage来说,去掉static main方法,实际是这样的:
public class E05_Storage {
String s = "Hello, World!";
int storage(String s) {
return s.length() * 2;
}
void print() {
System.out.println("storage(s) = " + storage(s));
}
},
即这个类有
一个属性字符串s
一个方法为storage
一个方法为print
要注意的是,程序是从static void main方法开始执行的,不是先调用print方法。
因此程序执行顺序是:
1、在static void main()方法中
实例化一个E05_Storage对象st
即
E05_Storage st = new E05_Storage();
2、调用这个实例的print方法
即
st.print();
于是就可以打印出来了。
其实对类StaticTest来说,去掉static属性和方法,这个类是空的
即
class StaticTest {
}
在java中非静态类是可以调用静态类的对象,也可以调用非静态类的对象,而静态类则只能调用静态类中的对象,不能调用非静态类中的对象。