자바에서 Object class는 다른 모든 클래스의 superclass입니다. Object 클래스에는 여러가지 메소드가 있는데, 그 중에서 AP CSA 시험에서 강조하는 2가지 메소드( toString, equals )에 대해서 알아보겠습니다.(아래는 AP CSA시험에서 제공하는 Java Quick Reference입니다.)
[2] toString( ) 메소드
Object 클래스 중에 오버라이드(Override)를 많이 하는 메소드 중의 하나로, toString()이 있습니다.
toString()메소드는 객체(object)의 특성을 출력하는 데에 많이 사용됩니다.
내가 만든 클래스에서 toString()을 오버라이드해서 사용해도 됩니다.
[예제1] 아래 코드를 실행해보고, 클래스간의 상속관계에서 toString()이 오버라이드 되어 있는 상태를 확인해 보세요.
위 코드는 Person 클래스가 Object 클래스의 toString() 메소드를 오버라이드 했습니다.
Person 클래스의 상속을 받은 Studen 클래스도 또한 toString() 메소드를 오버라이드 했습니다.
Person, Student 클래스는 각각 고유의 필드값도 가지고 있습니다.
[유제1] 아래의 조건을 만족하는 코딩을 추가하세요.
<조건> 1.Complete the subclass called APStudent that extends Student with a new attribute called APscore and override the toString() method to call the superclass method and then add on the APscore. 2.Uncomment the APStudent object in the main method to test it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Person {
privateString name;
public Person(String name) {
this.name = name;
}
publicStringtoString() {
return name;
}
}
class Student extends Person {
privateint id;
public Student(String name, int id) {
super(name);
this.id = id;
}
publicStringtoString() {
returnsuper.toString() +" "+ id;
}
}
class APStudent extends Student {
privateint score;
public APStudent(String name, int id, int score) {
super(name, id);
this.score = score;
}
// Add a toString() method here that calls the super class toString
}
publicclass Main {
publicstaticvoid main(String[] args) {
Person p =new Person("Sila");
Student s =new Student("Tully", 1001);
System.out.println(p); // call Person toString
System.out.println(s); // call Student toString
// Uncomment the code below to test the APStudent class