在最近的一个问题中,有人问过静态方法,其中一个答案表明你通常会用以下方法调用它们:
MyClassName.myStaticMethod();
Run Code Online (Sandbox Code Playgroud)
对此的评论还表明你也可以通过一个对象来调用它:
MyClassName myVar;
myVar.myStaticMethod();
Run Code Online (Sandbox Code Playgroud)
但它被认为是不好的形式.
现在在我看来,这样做实际上可以让我的生活更轻松,所以我不必担心什么是静态的(a).
是有一些问题,通过对象调用静态函数?显然你不想创建一个全新的对象来调用它:
Integer xyzzy;
int plugh = xyzzy.parseInt ("42", 10);
Run Code Online (Sandbox Code Playgroud)
但是,如果您已经有一个所需类型的对象,使用它是否有问题?
(a)显然,我不能用以下方法调用非静态方法:
MyClassName.myNonStaticMethod();
Run Code Online (Sandbox Code Playgroud)
但这不是我在这里问的问题.
我已经了解到,如果我们希望调用另一个类的静态方法,那么你必须在调用静态方法时编写类名.在下面的程序中,我在Employee_Impl类中创建了Employee类的对象,并使用该对象,我仍然可以访问该count方法.count如果static只使用类名访问方法,为什么它允许我在对象中使用方法?这是否意味着可以使用对象和类名来访问静态方法?
Employee.java
public class Employee{
static int counter = 0;
static int count(){
counter++;
return counter;
}
}
Run Code Online (Sandbox Code Playgroud)
Employee_Impl.java
class Employee_Impl
public static void main(String args[]){
Employee obj = new Employee();
System.out.println(obj.count());
System.out.println(Employee.count());
System.out.println(obj.count());
}
}
Run Code Online (Sandbox Code Playgroud)
output
1
2
3
Run Code Online (Sandbox Code Playgroud) 有人可以建议,为什么我不能在这里应用方法参考?
工作代码。
System.out.println(
Arrays.stream(str.split(" "))
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting())));
Run Code Online (Sandbox Code Playgroud)
编译错误,无法解析方法
System.out.println(
Arrays.stream(str.split(" "))
.collect(Collectors.groupingBy(Function::identity,Collectors::counting)));
Run Code Online (Sandbox Code Playgroud)