// 부모 메서드
class Point {
int x;
int y;
String getLocation() { //부모 메서드와 자식 메서드가 일치해야함
return "x :" + x + ", y :" + y;
}
}
// 자식 메서드
class Point3D extends Point {
int z;
String getLocation() { //부모 메서드와 자식 메서드가 일치해야함
"x :" + x + ", y :" + y + ", z :" + z;
}
}
class Parent {
void parentMethod() throws IOException, SQLException {
}
}
class Child extends Parent {
void parentMethod() throws IOException { //자식이 예외가 더 많아서는 안됨
}
}
class Parent {
void parentMethod() {}
}
class Child extends Parent {
void parentMethod() {} //오버라이딩
void parentMethod(int i) {} //오버로딩
void childMethod() {} //메서드 정의
void childMethod(int i) {} //오버로딩
void childMethod() {} //중복 정의(에러)
}
// 부모 메서드
class Point {
int x;
int y;
String getLocation() {
return "x :" + x + ", y :" + y;
}
}
// 자식 메서드
class Point3D extends Point {
int z;
String getLocation() {
"x :" + x + ", y :" + y + ", z :" + z;
}
}
public class OverrideTest {
public static void main(String[] args) {
MyPoint3D p = new MyPoint3D();
p.x = 3;
p.y = 5;
p.z = 7;
System.out.println(p.getLocation());
}
}
오버라이딩 이전 값
오버라이딩 값
class MyPoint3 extends Object{
int x;
int y;
// Object클래스의 toString()을 오버라이딩
public String toString() {
return "x: "+x+", y:"+y;
}
}
public class OverrideTest {
public static void main(String[] args) {
MyPoint3 p = new MyPoint3();
p.x = 3;
p.y = 5;
System.out.println(p);
System.out.println(p.toString());
System.out.println("p.x="+p.x);
System.out.println("p.y="+p.y);
// 이 4개는 모두 같은 뜻
}
}
class MyPoint3 extends Object{
int x;
int y;
//생성자
MyPoint3(int x, int y) {
this.x = x;
this.y = y;
}
// Object클래스의 toString()을 오버라이딩
public String toString() {
return "x:"+x+", y:"+y;
}
}
public class OverrideTest {
public static void main(String[] args) {
MyPoint3 p = new MyPoint3(3,5);
System.out.println(p);
}
}