2017-09-04 9 views
-3

なぜこのコードはコンパイルされません。私はJavaでPredicateを学びます。ここで私はすでに次のリンクInner Class InstantiationJava 8 Innnerクラスのインスタンス化

通過したコード

package com.java8.lambda.predicate; 

import java.util.ArrayList; 
import java.util.Date; 
import java.util.List; 
import java.util.function.Predicate; 
import java.util.stream.Collectors; 

import com.java8.lambda.pojo.Employee; 

public class PredicateSample { 
    public static void main(String[] args) { 
     Employee permanentEmployee = new Employee(70, "Jagmohan", "Sanyal", new Date(), 'M', 19900.87,"P"); 
     Employee tempEmployee = new Employee(70, "Shruti", "Bhatia", new Date(), 'F', 1990.87,"C"); 

     List<Employee> empList = new ArrayList<>(); 
     empList.add(permanentEmployee); 
     empList.add(tempEmployee); 

     PredicateSample predicateSample = new PredicateSample(); 
     //Code doesn't compile on this line due to non-visibility of EmployeePredicate class 
     //It fails with "PredicateSample.EmployeePredicate cannot be resolved to a type" 
     EmployeePredicate empPredicate = new PredicateSample().new EmployeePredicate(); 
    } 

} 

class EmployeePredicate { 

    public Predicate<Employee> getOlderEmployee(){ 
     return p -> p.getAge() > 60 && p.getEmploymentType().equalsIgnoreCase("P"); 
    } 

    public List<Employee> filter(List<Employee> employees, Predicate<Employee> p){ 
     return employees.stream().filter(p).collect(Collectors.toList()); 
    } 
} 

は、私はまた、他のサイトから行ってきましたが、問題を把握することができません。

+5

「EmployeePredicate」は、「PredicateSample」の内部クラスではありません。 –

答えて

2

クラスの内部クラスが必要です。

public class PredicateSample { 
    public static void main(String[] args) { 
     Employee permanentEmployee = new Employee(70, "Jagmohan", "Sanyal", new Date(), 'M', 19900.87,"P"); 
     Employee tempEmployee = new Employee(70, "Shruti", "Bhatia", new Date(), 'F', 1990.87,"C"); 

     List<Employee> empList = new ArrayList<>(); 
     empList.add(permanentEmployee); 
     empList.add(tempEmployee); 

     PredicateSample predicateSample = new PredicateSample(); 
     //Code doesn't compile on this line due to non-visibility of EmployeePredicate class 
     //It fails with "PredicateSample.EmployeePredicate cannot be resolved to a type" 
     EmployeePredicate empPredicate = new PredicateSample().new EmployeePredicate(); 
    } 

    // **inner** class. 
    class EmployeePredicate { 

     public Predicate<Employee> getOlderEmployee(){ 
      return p -> p.getAge() > 60 && p.getEmploymentType().equalsIgnoreCase("P"); 
     } 

     public List<Employee> filter(List<Employee> employees, Predicate<Employee> p){ 
      return employees.stream().filter(p).collect(Collectors.toList()); 
     } 
    } // < --- end of **inner** class 
} // < --- end of **outer** class. 
関連する問題