静态方法是类级方法,它们适用于Java中的Math类的实用方法.这些类通常需要一些输入,并提供所需的输出(例如Math.pow(4,5)).
实例方法更适用于整个对象.好的例子几乎是任何类的Java.还是,例如; FileInputStream,其中read()方法从底层流中读取数据.
静态方法的例子是
class Math(){
public static long multiply(long a, long b){
return a*b;
}
public static void main(String[]args){
System.out.println(Math.multiply());
}
}
Run Code Online (Sandbox Code Playgroud)
实例方法的示例可以是
class User(){
private String pass;
private String uname;
public User(String p,String u){
pass=p;
uname=u;
}
public boolean authenticate(){
if("secret".equals(this.pass) && "Grrrr".equals(this.uname){
return true;
}else{
return false;
}
}
public static void main(String[]args){
User u = new User("wrong secret","grrr");
System.out.println(u.authenticate());
}
}
Run Code Online (Sandbox Code Playgroud)
在第二个示例中,请注意以下事实:要使用实例方法,我们必须首先创建一个对象,然后才调用该方法.