(Method)Overriding

Modify method which is from parent.

Override : v.덮어쓰다

class Point {
    int x;
    int y;
    
    String getLocation() {
        return "x :" + x + ",y :"+y;
    }
}

class Point3D extends Point {
    int z;
    //Method declaration does not change, but contents change.
    String getLocation() {
        return "x :" + x + ",y : "+y + ",z : "+z;
    }
}
class Point extends Object{
    int x;
    int y;
    
    //Object클래스의 toString()을 오버라이딩. 
    public String getLocation() {//선언부는 똑같아야함!
        return "x :" + x + ",y :"+y;
    }
}

class Point3D extends Point {
    int z;
    //Method declaration does not change, but contents change.
    String getLocation() {
        return "x :" + x + ",y : "+y + ",z : "+z;
    }
}

Make code clear and simple using constructor and overriding

public class OverridngTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyPoint3 p = new MyPoint3(3, 5);//constructor
		System.out.println(p);//overriding toString method
		
//		p.x = 3;
//		p.y = 5;
		
		
//		System.out.println(p.toString());
//		System.out.println(p.x);
//		System.out.println(p.y);
	}

}
  • overriding condition

  1. method declartion must be same as parent class. : String getLocation() => return type, method name, parameter list

  2. access modifier <= parent class method access modifier. ex) public, protected, (dafult) private

  3. exception <= parent class method exception.

  • overloading and overriding

Technicall those are different.

  1. overloading : Define new method

  2. overriding : Modify inherited method contents

class Parent {
    void parentMethod() {}
}

class Child extends Parent {
    void parentMethod() {}//inherit method. overriding
    void parentMethod(int i) {}//overloading
    
    void childMethod() {}
    void childMethod(int i) {}//overloading
}

Last updated