class 자식클래스 **extends** 부모클래스 {
//필드
//생성자
//메소드
}
// 생성자가 명시적으로 선언되지 않았다면 컴파일러는 기본생성자를 생성
public DmbCellPhone() {
super();
}
public class People {
public String name;
public String ssn;
public People(String name, String ssn) {
this.name = name;
this.ssn = ssn;
}
}
public class Student extends People {
public int studentNo;
public Student(String name, String ssn, int studentNo) {
super(name, ssn); // 없으면 에
this.studentNo = studentNo;
}
}
Student 클래스의 생성자는 name, ssn, studentNo를 매개값으로 받아서 name과 ssn은 다시 부모 생성자를 호출하기 위해 매개값으로 넘겨줌
메소드 재정의 (오버라이딩)
super.부모메소드();
final
protected 접근제한
Cat cat = new Cat();
Animal animal = cat;
// Animal animal = new cat(); 도 가능
// 두 변수는 동일한 Cat 객체를 참조
public class Tire {
//필드
public int maxRotation; //최대 회전수
public int accumulatedRotation; //누적 회전수
public String location; //타이어의 위치
//생성자
public Tire(String location, int maxRotation) {
this.location = location; // 위치 초기화
this.maxRotation = maxRotation; // 누적 회전수 초기화
}
//메소드
public boolean roll() {
++accumulatedRotation; //누적 회전수 1 증가
if(accumulatedRotation<maxRotation) { // 정상 회전일 경우 실행
System.out.println(location + " Tire 수면: " + (maxRotation-accumulatedRotation) + "회");
return true;
} else { // 누적 = 최대 회전수 일 경우 실행
System.out.println("*** " + location + " Tire 펑크 ***");
return false;
}
}
}
public class Car {
//필드
Tire frontLeftTire = new Tire("앞/왼", 6);
Tire frontRightTire = new Tire("앞/오", 2);
Tire backLeftTire = new Tire("뒤/왼", 3);
Tire backRightTire = new Tire("뒤/오", 4);
//생성자
//메소드
int run() {
//모든 타이어 회전
//false리턴하는 메소드 있으면 stop 호출하고 해당 번호 리턴
System.out.println("[자동차가 달립니다.]");
if(frontLeftTire.roll()==false) { stop(); return 1; };
if(frontRightTire.roll()==false) { stop(); return 2; };
if(backLeftTire.roll()==false) { stop(); return 3; };
if(backRightTire.roll()==false) { stop(); return 4; };
return 0;
}
void stop() { // 펑크 났을때 실행
System.out.println("[자동차가 멈춥니다.]");
}
}
public class HankookTire extends Tire {
//생성자
public HankookTire(String location, int maxRotation) {
super(location, maxRotation);
}
//메소드
@Override //다른내용 출력하기 위해 roll() 오버라이딩
public boolean roll() {
++accumulatedRotation;
if(accumulatedRotation<maxRotation) {
System.out.println(location + " HankookTire 수명: " + (maxRotation-accumulatedRotation) + "ȸ");
return true;
} else {
System.out.println("*** " + location + " HankookTire 펑크 ***");
return false;
}
}
}
public class CarExample {
public static void main(String[] args) {
Car car = new Car();
for(int i=1; i<=5; i++) {
int problemLocation = car.run();
switch(problemLocation) {
case 1:
System.out.println("앞/왼 HankookTire로 교체");
car.frontLeftTire = new HankookTire("앞/왼", 15);
break;
case 2:
System.out.println("앞/오 KumhoTire로 교체");
car.frontRightTire = new KumhoTire("앞/오", 13);
break;
case 3:
System.out.println("뒤/왼 HankookTire로 교체");
car.backLeftTire = new HankookTire("뒤/왼", 14);
break;
case 4:
System.out.println("뒤/오 KumhoTire로 교체");
car.backRightTire = new KumhoTire("뒤/오", 17);
break;
}
System.out.println("----------------------------------------");
}
}
}
public class Vehicle {
public void run() {
System.out.println("차량이 달립니다");
}
}
public class Driver {
public void drive(Vehicle vehicle) {
vehicle.run();
} // drive 메소드에서 Vehicle 타입의 매개값 받아서 run() 메소드 호출
}
public class Bus extends Vehicle {
@Override
public void run() {
System.out.println("버스가 달립니다.");
}
}
public class Taxi extends Vehicle {
@Override
public void run() {
System.out.println("택시가 달립니다.");
}
}
public class DriverExample {
public static void main(String[] args) {
Driver driver = new Driver();
Bus bus = new Bus();
Taxi taxi = new Taxi();
// 자식 객체가 재정의한 run() 메소드 실행
driver.drive(bus); // 자동 타입 변환 Vehicle vehicle = bus;
driver.drive(taxi); // 자동 타입 변환 Vehicle vehicle = taxi;
// 버스가 달립니다.
// 택시가 달립니다.
}
}
public class Parent {
public String field1;
public void method1() {
System.out.println("Parent-method1");
}
public void method2() {
System.out.println("Parent-method2");
}
}
public class child extends Parent {
public String field2;
public void method3() {
System.out.println("Child-method3");
}
}
public class ChildExample {
private static Child ;
public static void main(String[] args) {
Parent parent = new Child(); // 자동 타입 변환
parent.field1 = "data1";
parent.method1();
parent.method2();
/* 불가능
parent.field2 = "data2";
parent.method3();
*/
Child = (Child) parent; // 강제 타입 변환
child.field2 = "yyy";
child.method3();
}
}
// 출력결과
Parent-method1
Parent-method2
Child-method3
public void method(Parent parent) {
if(parent instanceof Child) {
// parent가 Child 타입으로 생성되었다면 true, 아니면 false
public abstract class 클래스 {…}
public abstract class Phone {
public String owner;
public Phone(String owner) {
this.owner = owner;
}
public void turnOn() {
System.out.println("폰 전원을 켭니다.");
}
public void turnOff() {
System.out.println("폰 전원을 끕니다.");
}
}
public class SmartPhone extends Phone {
public SmartPhone(String owner) {
super(owner);
}
public void internetSearch() {
System.out.println("인터넷 검색을 합니다.");
}
}
public class PhoneExample {
public static void main(String[] args) {
//Phone phone = new Phone(); 불가능
SmartPhone smartPhone = new SmartPhone("홍길동");
smartPhone.turnOn(); //Phone 메소드
smartPhone.internetSearch();
smartPhone.turnOff();
}
}
// 출력결과
폰 전원을 켭니다.
인터넷 검색을 합니다.
폰 전원을 끕니다.
public abstract void 메소드이름();
public abstract class Animal {
public String kind;
public void breathe() {
System.out.println("숨을 쉽니다.");
}
public abstract void sound(); //추상 메소드
}
public class Dog extends Animal {
public Dog() {
this.kind = "포유류";
}
@Override
public void sound() {
System.out.println("멍멍");
}
}
public class Cat extends Animal {
public Cat() {
this.kind = "포유류";
}
@Override
public void sound() {
System.out.println("야옹");
}
}
public class AnimalExample {
public static void main(String[] args) {
Dog dog = new Dog();
Cat cat = new Cat();
dog.sound();
cat.sound();
// 멍멍
// 야옹
Animal animal = null;
// 자동 타입 변환 및 재정의된 메소드 호출
animal = new Dog();
animal.sound();
animal = new Cat();
animal.sound();
// 멍멍
// 야옹
// 메소드 다형성
animalSound(new Dog());
animalSound(new Cat());
}
public static void animalSound(Animal animal) { // 자동 타입 변환
animal.sound(); // 재정의된 메소드 호출
}
// 멍멍
// 야옹
}