overriding

염지은·2021년 12월 12일
0

java

목록 보기
25/45

[ 오버라이딩(Overriding) *** ]

  • 부모클래스의 메소드를 자식클래스에서 수정하고자 할때 오버라이딩을 한다
  • 만드는 방법 : 부모클래스의 메소드명,파라미터갯수,타입,리턴형 모두 일치해야 한다.
  • 자식클래스에서 오버라이딩할때 접근지정자의 범위가 좁아지면 안된다.
    예)
    class Parent{
    public void print(){}
    }
    class Child extends Parent{
    public void print(){ //오버라이딩
    ...
    }
    public void print(String s){ //오버로딩
    ...
    }
    }
    class Shape{
    	protected int x; //x좌표
    	protected int y; //y좌표
    	public Shape(int x,int y) {
    		this.x=x;
    		this.y=y;
    	}
    	public void draw() {
    		System.out.println("도형그릴 좌표:x=" + x +",y=" + y);
    	}
    }
    class Rect extends Shape{
    	public Rect(int x,int y) {
    		super(x,y);
    	}
    	public void draw() { //오버라이딩
    		System.out.println(x +"," + y + "의 위치에 사각형 그리기");
    	}
    	public void draw(String color) { //오버로딩
    		System.out.println(color +"색상의 사각형 그리기");
    	}
    }
    public class Test01_오버라이딩 {
    	public static void main(String[] args) {
    		Rect r=new Rect(100,200);
    		r.draw();
    		r.draw("빨강");
    	}
    }

0개의 댓글