Day 12 :) Overriding, This, Super

Nux·2021년 9월 15일
0

자바웹개발

목록 보기
12/105
post-thumbnail

오버라이딩

  • 상속받은 상위클래스의 내용을 하위클래스에서 재정의하는 것.
1. 부모클래스
public class Parent{
	int x;
    int y;
    String getLocation(){
    	return x,y;
    }
}    
2. 자식클래스
public class Child extends Parent{
	int z;
    String getLocation(){
    	return x, y, z;
    }
}

부모클래스에서는 존재하지 않았던 getLocation의 int z가 자식클래스에서 생성됨

오버라이딩의 조건

  • 메서드의 내용만 변경하는 것이므로 메서드의 선언부(반환값, 메서드명, 매개변수)는 변동 없음
  • 접근제어자는 부모클래스보다 좁은 범위로 변경 불가
    ex) parent: protected -> child: public, protected만 가능
  • 부모클래스보다 많은 예외(throw) 선언 불가

오버라이딩과 오버로딩

  • 오버라이딩: 부모클래스 메서드의 내용을 변경하는 것
  • 오버로딩: 메서드에 새로운 정의를 추가하는 것(중복정의)
1. parent class
public class Parent{
	void parentMethod(){
    }
2. child class
public class Child extends parents{
	void parentMethod(){	// 오버라이딩
    	int a = 1;	
    }
    void parentMethod(int x){}	// 오버로딩
    
    void childMethod(){}
    void childMethod(int x){}	// 오버로딩
}
      중복정의          재정의
메서드 이름 동일메서드 이름 동일
조건매개변수 갯수/타입 다르게매개변수 갯수/타입 같게
반환타입, 접근제한자 상관 없음반환타입 동일, 접근제한자 동일하거나 하위
이용시점매개변수만 다르고 내용이 비슷할 때부모로부터 상속받은 메서드의 일부가 자신과 다를때
장점비슷한 기능을 일관된 이름으로 사용객체가 달라도 사용법은 동일

키워드 this,super

this, super

  • this: 객체 자기자신의 주소값을 갖고 있음
  • super: 자신의 상위객체에 대한 주소값 갖고 있음.
    부모클래스와 메서드명이 겹칠 경우, 자식클래스 메서드에서 super.메서드명으로 사용
1. parent class
public class Parent{
	public void sample(){
    	System.out.println("부모클래스의 메서드 sample");
    }
}
2. child class
public class Child extends Parent{
	public void sample(){
    	super.sample();			// ★super 키워드로 상위 클래스의 메서드 호출
        System.out.println("자식클래스의 메서드 sample")
    }
    
    public static void main(String[]args){
    	Child abc = new Child();	// Child 객체 생성
        abc.sample()
    }
    
}

최종출력:
부모클래스의 메서드 sample
자식클래스의 메서드 sample

this(), super()

  • this(): 같은 클래스의 다른 생성자를 호출할 때 사용
public class Sample{
	int no;
    int price;
    int discountPrice;

    Sample(int no, int price, int discountPrice){
        this.no = no;
        this.price = price;
        this.discountPrice = discountPrice;
    }
    
    Sample(int no, int price){
    	this.Sample(1, 10000, 8000)
    }
}
  • super(): 부모 클래스로부터 상속받은 필드나 메소드를 자식 클래스에서 참조하는 데 사용
1. parent class
public class Product{
	Product(){}
	Product(int no, int price){}
}
2. child class
public class Book extends Product{
	String title;
    Book(){
    	super(1, 10000)
        title = "자바의 정석"
    }
    
    public static void main(String[]args){
    	Product abc = new Product();
        abc.Book();			// 출력 내용:1, 10000, 자바의정석
    }
}

0개의 댓글