Java小问题:::::::::::::::::::::::::

来源:百度知道 编辑:UC知道 时间:2024/06/03 16:31:15
public static void printInfo(Student stu)

class Student
{
String number;
String name;
double score;
boolean sex;
}
public class StudentTest
{
public static void main(String args[])
{
Student stu=new Student();
stu.number="0001";
stu.name="zhangsan";
stu.score=90;
stu.sex=true;
printInfo(stu);
}

public static void printInfo(Student stu)
{
System.out.println("my name is:"+stu.name);
System.out.println("my number is:"+stu.number);
System.out.println("my score is:"+stu.score);
if(stu.sex)
System.out.println("my sex is male");
else
System.out.println("my sex is female);
}

}

public static void printInfo(Student stu)
为什么这个方法要是static的呢?
不是不行吗?

static 是申明一个静态的方法 这样你就可以不用new 声名对象再调用方法。

实际上printInfo(stu);
相当于StudentTest.printInfo(stu);
因为他们是在同一个类中的方法 可以省略掉StudentTest.

如果你把printInfo的 static 声明去掉

完整的在main方法中就要 new StudentTest().printInfo(stu);
因为在同一类中 可以写成this.printInfo(stu);

另外如果你做了企业级的应用方案 static的方法写时一定要谨慎。因为在服务启动时static是要优先加载的。 如果是非常大的资源读取写入操作,或者过多的static方法,就会使服务器在启动时就挂掉。

其实也没什么,就是定义成了类的静态方法,可以直接写方法名就能调用,也就是说这个方法是属于类的,不写也可以,不过你要声明一个
StudentTest st = new StudentTest();那么这个方法就是属于对象的。
然后用 st.printInfo(stu); 就可以了。
至于static有什么好处,你可以在百度上查到很多学习资料。

如果不是static的话不能在main方法中直接调用,如果要调用,先要new出一个对象的实例,然后才可以调用,但是加上static的话就可以直接在main方法里调用了,不需要实例化了