책에서 샘플 클래스를 수정하고 제네릭을 사용하도록 변환하여 작동 원리를 알려줍니다. 아래에서 내 코드를 볼 수 있습니다. 범용 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
무엇이 질문입니까? – vanza
제네릭에 적합하지 않습니다. 'id'가 String이 아닌, 또는 나이가 int가 아닌 것으로 이해하는 것이 맞습니까? 그랬더라도 getName이 Person을 구현하기 위해 String을 리턴해야한다는 문제가있다. 그래서 이름은 꽤 많이 String으로 제한됩니다. –
안녕 마이클, 나는 그걸 아무것도 쓸 생각이 없었어. 나는 그것의 주위에 나의 머리를 얻는보기로 다만 그것을 사용하고있다. –