Frog is cry
메소드 재정의(오버라이딩) 본문
package 메소드재정의.ex01;
public class SportsCar extends Car{
@Override
public void speedUp() {
speed += 10;
}
// public void stop() { // final로 상속 불가
//
// }
}
package 메소드재정의.ex01;
public class Car {
// 필드
public int speed;
// 생성자
// 메소드
public void speedUp() {
speed += 1;
}
public final void stop() {
System.out.println("차를 멈춤");
speed = 0;
}
}
package 메소드재정의.ex02;
public class Calculator {
double areaCircle(double r) {
System.out.println("Calculator 객체의 areaCircle() 실행");
return 3.14159 *r *r;
}
}
package 메소드재정의.ex02;
public class Computer extends Calculator{
@Override // 어노테이션이라함
double areaCircle(double r) {
// 재정의할땐 부모것과 같아야함 접근권한제어자 중 좀 더 넓은 범위로 변경하는것은 가능
System.out.println("Computer 객체의 areaCircle() 실행");
return Math.PI *r *r;
}
}
package 메소드재정의.ex02;
public class Computer_Ex {
public static void main(String[] args) {
int r = 10;
Calculator myCalc = new Calculator();
System.out.println("원의 면적 : " + myCalc.areaCircle(r));
Computer myCom = new Computer();
System.out.println("원의 면적 : " + myCom.areaCircle(r));
}
}
package 메소드재정의.ex03;
public class Airplane {
public void land() {
System.out.println("착륙합니다.");
}
public void fly() {
System.out.println("일반비행 합니다.");
}
public void takeOff() {
System.out.println("이륙합니다.");
}
}
package 메소드재정의.ex03;
public class SuperSonicAirplane extends Airplane{
public static final int NORMAL = 1;
public static final int SUPERSONIC = 2;
public int flyMode = NORMAL;
@Override
public void fly() {
if(flyMode == SUPERSONIC) {
System.out.println("초음속 비행 합니다.");
}else {
super.fly(); // 부모의 내용을 가져오기위해 super.을 붙임
}
}
}
package 메소드재정의.ex03;
public class SuperSonicAirplane_Ex {
public static void main(String[] args) {
SuperSonicAirplane sa = new SuperSonicAirplane();
sa.takeOff();
sa.fly();
sa.flyMode = SuperSonicAirplane.SUPERSONIC;
sa.fly();
sa.flyMode = SuperSonicAirplane.NORMAL;
sa.fly();
sa.land();
}
}
package 메소드재정의.ex04;
public final class Member {
}
package 메소드재정의.ex04;
public class VeryImportantPerson { //extends Member > Member가 final로 상속 불가
}
Comments