Goru
[Java] 오버라이딩 본문
오버라이딩이란?
조상 클래스로부터 상속은 서드의 내용을 변경하는 것을 오버라이딩이라고 한다.
class Point{
int x;
int y;
String getLocation(){
return " x : " + x + ", y: "+y;
}
}
class Point3D extends point{
int z;
String getLocation() { //오버라이딩
return " x : " + x +", y:"+y+",z:"+z;
}
}
오버라이딩의 조건
자손 클래스에서 오버라이딩하는 메서드는 조상 클래스의 메서드와
- 이름이 같아야 한다.
- 매개변수가 같아야 한다.
- 반환타입이 같아야 한다.
※ 선언부가 서로 일치해야 한다
1. 접근 제어자는 조상클래스의 메서드보다 좁은 범위로 변경할 수 없다.
2. 조상 클래스의 메서드보다 많은 수의 예외를 선언할 수 없다.
3. 인스턴스 메서드를 static 메서드로 또는 그 반대로 변경할 수 없다.
super
super는 자손 클래스에서 조상클래스로부터 상속받은 멤버를 참조하는데 사용되는 참조 변수이다. 상속받은 멤버와
자신의 멤버와 이름이 같을 때는 super를 붙여서 구별할 수 있다.
public class SuperTest {
public static void main(String[] args) {
Child c = new Child();
c.method();
}
}
class Parent{
int x = 10;
}
class Child extends Parent{
void method() {
System.out.println("x="+x);
System.out.println("this.x="+this.x);
System.out.println("super.x="+super.x);
}
}
x=10
this.x=10
super.x=10
public class SuperTest2 {
public static void main(String[] args) {
Child c = new Child();
c.method();
}
}
class Parent{
int x = 10;
}
class Child extends Parent{
int x = 20;
void method() {
System.out.println("x="+x);
System.out.println("this.x"+this.x);
System.out.println("super.x"+super.x);
}
}
x=20
this.x = 20
super.x = 10
super( ) - 조상 클래스의 생성자
super()는 조상 클래스의 생성자를 호출하는데 사용된다.
Object클래스를 제외한 모든 클래스의 생성자 첫 줄에 생성자,this() 또는 super(),를 호출해야 한다. 그렇지 않으면 컴파일러가 자동적으로 'super();'를 생성자의 첫줄에 삽입한다. |
public class PointTest {
public static void main(String[] args) {
Point3D p3 = new Point3D(1,2,3);
}
}
class Point{
int x, y;
Point(int x, int y){
this.x = x;
this.y = y;
}
String getLocation() {
return "x:"+x+",y:"+y;
}
}
class Point3D extends Point{
int z;
Point3D(int x, int y, int z){
super(x,y);
this.z = z;
}
String getLocation() {
return "x:"+x+",y:"+y+",z:"+z;
}
}
public class PointTest2 {
public static void main(String[] args) {
Point3D p3 = new Point3D();
System.out.println("p3.x=" +p3.x);
System.out.println("p3.y=" +p3.y);
System.out.println("p3.z=" +p3.z);
}
}
class Point{
int x = 10;
int y = 20;
Point (int x, int y){
this.x = x;
this.y = y;
}
}
class Point3D extends Point{
int z = 30;
Point3D(){
this(100, 200, 300); //Point3D(int x, int y, int z)를 호출한다.
}
Point3D(int x, int y, int z){
super(x,y); //Point(int x, int y)를 호출한다.
this.z = z;
}
}
p3.x=100
p3.y=200
p3.z=300
'Java' 카테고리의 다른 글
[JAVA]제어자 (0) | 2022.01.21 |
---|---|
[Java]package 와 import (0) | 2022.01.20 |
[Java] 클래스간의 관계- 포함관계 (0) | 2022.01.19 |
[Java] 상속 (0) | 2022.01.19 |
[Java] 변수의 초기화 (0) | 2022.01.19 |