2015-02-06 2 views
2

책에서 샘플 클래스를 수정하고 제네릭을 사용하도록 변환하여 작동 원리를 알려줍니다. 아래에서 내 코드를 볼 수 있습니다. 범용 A, B 및 C는 String String 및 int로 사용됩니다.Java의 일반 사항을 이해하려고 시도합니다.

public class Student<A,B,C> implements Person { 
    A id; 
    B name; 
    C age; 

    public Student(A i, B n, C a) { 
     id = i; 
     name = n; 
     age = a; 
    } 

    protected int studyHours() {return age/2;} 
    public A getID() {return id;} 
    public B getName() {return name;} 
    public C getAge() {return age;} 
    public boolean equals(Person other) { 
     if(!(other instanceof Student)) return false; 
     Student s = (Student) other; 
     return id.equals(s.id); 
    } 
    public String toString() { 
     return "Student(ID: " + id + ", Name: " + name + ", Age: " + age + ")"; 
    } 
    public static void main(String[] var0) { 
     Student<String,String,int> studentOne = new Student("123", "Guillermo", 34); 
     Student<String,String,int> studentTwo = new Student("345", "Cheryl", 35); 
     int numberOfStudyHours; 

     numberOfStudyHours = studentOne.studyHours(); 
     System.out.println("Guillermo studies " +numberOfStudyHours+ " hours"); 

    } 
} 

는 사람 인터페이스는 전문가의지도가 크게 감상 할 수

public interface Person { 
    public boolean equals(Person other);  //is this the same person? 
    public String getName(); 
    public int getAge(); 
} 

다음과 같습니다. 다음

public class Student<A,B,C> implements Person<B,C> { 
    A id; 
    B name; 
    C age; 
    ... 
} 

But this isn't really a good use of generics

public interface Person<B,C> { 
    public boolean equals(Person other);  //is this the same person? 
    public B getName(); 
    public C getAge(); 
} 

과 : 그것은 당신이 당신의 인터페이스를 변경해야처럼 보이는 당신의 예를 들어

Student.java:4: error: Student is not abstract and does not override abstract method getAge() in Person 
     public class Student<A,B,C> implements Person { 
      ^
    Student.java:18: error: getAge() in Student cannot implement getAge() in Person 
      public C getAge() {return age;} 
        ^
     return type C is not compatible with int 
     where C is a type-variable: 
     C extends Object declared in class Student 
    Student.java:17: error: getName() in Student cannot implement getName() in Person 
      public B getName() {return name;} 
        ^
     return type B is not compatible with String 
     where B is a type-variable: 
     B extends Object declared in class Student 
    Student.java:15: error: bad operand types for binary operator '/' 
      protected int studyHours() {return age/2;} 
               ^
     first type: C 
     second type: int 
     where C is a type-variable: 
     C extends Object declared in class Student 
    Student.java:28: error: unexpected type 
       Student<String,String,int> studentOne = new Student("123", "Guillermo", 34); 
            ^
     required: reference 
     found: int 
    Student.java:29: error: unexpected type 
       Student<String,String,int> studentTwo = new Student("345", "Cheryl", 35); 
            ^
     required: reference 
     found: int 
+4

무엇이 질문입니까? – vanza

+6

제네릭에 적합하지 않습니다. 'id'가 String이 아닌, 또는 나이가 int가 아닌 것으로 이해하는 것이 맞습니까? 그랬더라도 getName이 Person을 구현하기 위해 String을 리턴해야한다는 문제가있다. 그래서 이름은 꽤 많이 String으로 제한됩니다. –

+0

안녕 마이클, 나는 그걸 아무것도 쓸 생각이 없었어. 나는 그것의 주위에 나의 머리를 얻는보기로 다만 그것을 사용하고있다. –

답변

0

:이 오류를 얻고있다. 또한 제네릭에는 int 또는 다른 프리미티브를 사용할 수 없습니다. Integer 또는 다른 복싱 클래스를 사용해야합니다.

+1

" udent.java:4 : 오류 : 학생이 추상 클래스가 아니며 abstract 메소드 getAge()를 재정의하지 않습니다"라는 오류 메시지를 읽는 것을 고려하십시오. 이는 클래스에 구현 된 모든 인터페이스가 지정된 메서드를 재정의해야 함을 의미합니다. 같은 메소드 시그 니챠를 가지는 인터페이스 Boggartfly

+0

@Boggartfly 오른쪽 '학생'은 추상적이 아니고'Person' 인터페이스를 구현합니다. 즉'Person'에 정의 된 모든 메소드를 구현해야합니다. 당신은'public C getAge();를 구현할 필요가있을 것입니다, 예를 들어,'public C getAge() {return age; }'에서'학생'. –

+0

정확히 무슨 뜻이야 !! 내 의견을 upvote 마십시오. 나는 진지하게 약간의 담당자가 필요하다. – Boggartfly

1

generics가 의미가있는 곳의 더 좋은 예를 보려면 다양한 Java Collections 클래스를 살펴보십시오. 예를 들어, 무엇이든 다른 것 (String to Integer, Integer to String, Integer to Integer, Person to String)으로 Map을 만드는 것이 합리적 일 수 있습니다. 당신은

Map<Person,Person> motherMap = new HashMap<>(); 

하나 개의 클래스는 모든 맵을 구현, 그러나 그것의 종류와 각각의지도를 인스턴스화 할 컴파일러와 IDE get() 방법에 주어져야 키의 종류를 알고, 어떤 결과 유형 get-go에서 많은 코딩 오류를 방지합니다.

제네릭을 잘 사용하는 예제를 찾는 또 다른 곳은 Google 라이브러리입니다 (GuavaExplained 참조). 연습 연습에서는

, 당신은 트리 노드가 컴파일 오류에 대한 동일한 제네릭 형식 T.

의 모든입니다 왼쪽과 오른쪽 자식 노드를 가진 이진 트리를 구현하는 시도 할 수, 제네릭은 사용할 수 없습니다 boolean 및 int와 같은 소문자 유형 - 대신 Boolean 및 Integer를 사용할 수 있습니다. 또한 인터페이스는 일반적으로 다음과 같이 일반적인 것입니다. HashMap<K,V> implements Map<K,V>

관련 문제