-2

I get this piece of code and I wonder why method task1 was called as Exam.task1. I tried modificate call as task1 and everything is ok. I know that static methods must be invoked from class, but why in this example code works without that kind of call?

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Predicate;


public class Exam {

    public static <T> void task1(Iterable<T> collection,Predicate<T> filter,Consumer<T> action){
        Set<T> set = new HashSet<>();
        for(T data : collection){
            if(filter.test(data) && set.add(data)){
                action.accept(data);
            }
        }
    }

    public static void main(String[] args) {
        List<String> list = Arrays.asList("c","d","a","a","de","e","gt","d","f","e");
        List<String> dest = new ArrayList<>();

        Exam.task1(list,str -> str.length() == 1, str -> dest.add(str)); 

        for(String s : dest){
            System.out.format("%s ",s);
        }
    }
}
few
  • 1

1 Answers1

0

Because main is a static method and you are in the same class, so Exam.task1 is implicit.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Yes, it's comparable to `this` being implicit inside methods, so if a class has field `x`, then you don't need to type `this.x` to refer to it inside methods. – DavidS Feb 15 '16 at 17:52
  • @DavidS Unless `x` also happens to be a local variable – OneCricketeer Feb 15 '16 at 17:54