본문 바로가기
강의

0112 Java lec06 chap07[상속]상속 + 타입 변환과 다형성 p310~356

by IT새내기IM 2023. 1. 11.

class member = Constructor + field + Method+ 

"Parameter는 메서드 선언의 변수 목록을 나타냅니다. Argument는 메서드가 호출될 때 전달되는 실제 값입니다.

상속 inheritance 는
부모클래스의 멤버를 자식클래스에게 물려주는것 부모를 상위/ 하위or파생 //생성자만들때 부모의 매개변수를 가진 생성자를 쓸때는
super(매개변수1,매개변수2)와 같이 부모쪽으로 물리고 자식은 this함수를 통해 나머지 매개변수를 입력해야함.
ex)         public Tire(String location,int maxRotation) {
this.location = location;
this.maxRotation = maxRotation;
}
public Hankook(String location,int maxRotation) {
super(location, maxRotation);
}


자바에서는 명령어를 통해 자식이 부모를선택해서 상속받는것 
상속하는 이유 부모클래스의 수정으로 모든 자식클래스들도 수정되는 효과를 가져오기 때문임.
같은클래스면 extends 다른 인터페이스면 implement를 통해 상속을받음

class 자식클래스 extends 부모클래스{
//필드
//생성자
//메소드
}

자식이 다 가지고 있으니 자식의 객체를 생성해야함., 자식개체 생성시 부모객체가먼저생성되고 그다음에 자식객체가 생성됨

만약 생성자를 명시적으로 선언하지 않았다면 컴파일러는 다음과같은 기본생성자를 생성
public DmbCellPhone() {
super();
}
이 때 super는부모의 기본 생성자를 호출
부모 생성자도 선언되지 않았지만 컴파일러에 의해 기본 생성자가 만들어짐.


상속받은클래스는 모델링하지않음  MVC패턴중 M에서는 x
M 데이터베이스 테이블 칼럼

Cal c = new Cal(); // 부모클래스 , 부모 생성자
System.out.println(c.ac(r));
Com c1 = new Com(); // 자식 클래스 , 자식생성자
System.out.println(c1.ac(r));
Cal c2 = new Com(); // 부모클래스,자식 생성자 자주씀중요
System.out.println(c2.ac(r));
//자식객체로 부모생성자를 만들순 없다. Com c4 = new Cal();

우클릭 - source -override 를 통해 메소드를 재정의가능

필드에 final = 초기값설정후 더이상 변경 X 
클래스와 메소드에 final이 설정되면 final 클래스는 최종적인 클래스가 되어  상속할수 없게됨 
final 메소드는 최종적인 메소드이므로 재정의할수없게됨

//자동 타입변환 P1 p = c; 부모클래스에 선언된 필드와 메소드만 접근가능 
// 변수는 자식객체를 참조하지만 변수로 접근 가능한 멤버는 부모클래스멤버로만 한정됨. 
// 예외가 있으면 메소드가 자식클래스에서 재정의 되었으면 자식클래스의 메소드가 대신 호출됨!!
자동타입변환

클래스의 변환은 상속관계에 있는클래스 사이에서 발생 자식은 부모타입으로 자동타입변환이 가능

필요한 이유 : 다형성을 위해서
필드의 타입을 부모타입으로 선언하면 //자식의 재정의를 통해 (타이어교체행위)// 다양한 자식 객체들이 저장될수 있기 때문임.

example )

Cat과 Dog는 Animal의 특징과 기능을 가지고있기때문에 부모와 동일하게 취급될 수있다는 뜻

Cat값을넘기든 Dog값을 넘기든 Animal로 받기위해서 사용

int의 default값은 0임

변수 타입에 따른 default값

자료형(변수 타입) 기본값
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\n0000'
boolean false
참조형 변수(String or any Object) null

 

부모 cellPhone 자식 DmbCellPhone + 메인Test  Paga311~313

package ex01;

public class CellPhone {
	String model;
	String color;
	
	void poweron() {System.out.println("전원을 켭니다.");};
	void powerOff() {System.out.println("전원을 끕니다.");};
	void bell() {System.out.println("벨이 울립니다.");};
	void sendVoice(String message) {System.out.println("자기: " + message);};
	void receiveVoice(String message) {System.out.println("상대방: " + message);};
	void hangUp() {System.out.println("전화를 끊습니다.");};
	
}

package ex01;

public class DmbCellPhone extends CellPhone {
	
	int channel;
	//String model; 부모클래스의 메소드 필드 생성자를를 쓸수있음
	//String color;
	
	DmbCellPhone(String model,String color, int channel){
		this.model = model;
		this.color = color;
		this.channel = channel;
	}
	
	void turnOnDmb() {
		System.out.println("채널 " + channel + "번 DMB 방송 수신을 시작합니다.");
	}
	void changeChannelDmb(int channel) {
		this.channel = channel;
		System.out.println("채널 " + channel + "번으로 바꿉니다.");
	}
	void turnOffDmb() {
		System.out.println("DMB 방송 수신을 멈춥니다.");
	}
}


package ex01;

public class Test {

	public static void main(String[] args) {
		
		DmbCellPhone c = new DmbCellPhone ("자바폰","검정",10);
		
		System.out.println("모델: " + c.model);
		System.out.println("색상: " + c.color);
		
		System.out.println("채널: " + c.channel);
		
		c.poweron();
		c.bell();
		c.sendVoice("여보세요.");
		c.receiveVoice("안녕하세요 홍길도이에요");
		c.sendVoice("아 네에 반갑습니다");
		c.hangUp();
		
		c.turnOnDmb();
		c.changeChannelDmb(12);
		c.turnOffDmb();

	}

}

부모 People +  자식 Student + Test2

 

package ex01;

public class People {
	public String name;
	public String ssn;
	
	public People(String name, String ssn) {
		this.name = name;
		this.ssn = ssn;
	}
}

package ex01;

public class Student extends People {
	public int studentNo;
	
	
	public Student(String name, String ssn, int studentNo) {   //부모에 맞게끔 상속받아야함
		super(name, ssn);
		this.studentNo = studentNo;
	}
}

package ex01;

public class Test2 {

	public static void main(String[] args) {
		Student s = new Student("신성은","123456-123457",1);
		System.out.println("name : " + s.name);
		System.out.println("ssn : " + s.ssn);
		System.out.println("studentNo : " + s.studentNo);

	}

}

Cal+Com+ComTest Page318

package sec01.exam03;

import java.util.Calendar;

public class Cal {
	
	double ac(double r) {
		System.out.println("Cal 클래스 객체 ac() 실행");
		return 3.14 * r * r; // 원의 넓이
	}
}

package sec01.exam03;

public class Com extends Cal{

	@Override //재정의하자
	double ac(double r) {
		System.out.println("Com 클래스 객체 ac()실행");
		return Math.PI * r * r; //원의 넓이
	}
	
}

package sec01.exam03;

import java.util.ArrayList;
import java.util.List;

public class ComTest {
	public static void main(String[] args) {
		int r = 10;
		
		Cal c = new Cal(); // 부모클래스 , 부모 생성자
		System.out.println(c.ac(r));
		Com c1 = new Com(); // 자식 클래스 , 자식생성자
		System.out.println(c1.ac(r));
		Cal c2 = new Com(); // 부모클래스,자식 생성자 중요
		System.out.println(c2.ac(r));
		//자식객체로 부모생성자를 만들순 없다. Com c4 = new Cal();
	}
}

부A+모B+BTEST 320~321

 

package sec01.exam03;

public class A {
	public void land() {
		System.out.println("착륙합니다.");
	}
	public void fly() {
		System.out.println("일반비행합니다.");
	}
	public void takeeOff() {
		System.out.println("이륙합니다.");
	}
}

package sec01.exam03;

public class B extends A{
	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();
		}
	}
}

package sec01.exam03;

public class BTest {

	public static void main(String[] args) {
		B b = new B();
		b.takeeOff();
		b.fly();
		b.flyMode = b.SUPERSONIC;
		b.fly();
		b.flyMode = b.NORMAL;
		b.fly();
		b.land();
	}

}

Parents + Child + CTest P331 (부모 생성자 매개변수 많은순서대로 자식 생성자 매개변수 많은 순서대로 실행됨)

package sec01.exam03;

public class P {
	public String nation;
	
	public P() {
		this("대한민국");
		System.out.println("Parent() call");
	}

	public P(String nation) {
		this.nation = nation;
		System.out.println("Parent(String nation) call");
	}
}

package sec01.exam03;

public class C extends P {
	private String name;
	
	public C() {
		this("홍길동");
		System.out.println("C() 기본 생성자");
	}
	
	public C(String name) {
		this.name = name;
		System.out.println("C(String name) 매개변수 생성자");
	}
}

package sec01.exam03;

public class CTest {

	public static void main(String[] args) {
		C c = new C();
	}

}

P1+C1+C1Test Page336~337

package ex02;

public class P1 {
	
	public void m1() {
		System.out.println("P-m1()");
	}
	public void m2() {
		System.out.println("P-m2()");
	}
}

package ex02;

public class C1 extends P1 {

	@Override //내용을 다른걸로 재정의하고싶어!
	public void m2() {
		// TODO Auto-generated method stub
		System.out.println("C-m2()");
	}
	
	public void m3() {
		System.out.println("C-m3()");
	}
	
}

package ex02;

public class C1Test {

	public static void main(String[] args) {
		C1 c = new C1();
		c.m1();
		c.m2();
		c.m3(); //자식은 부모것을 다가지고 있어서 사용가능함.
		
		P1 p = c;  //자동 타입변환하면 부모클래스에 선언된 필드와 메소드만 접근가능 
		// 변수는 자식객체를 참조하지만 변수로 접근 가능한 멤버는 부모클래스멤버로만 한정됨. 
		// 예외가 있으면 메소드가 자식클래스에서 재정의 되었으면 자식클래스의 메소드가 대신 호출됨!!
		p.m1(); 
		p.m2(); //재정의된 메소드호출
		//  p.m3(); 불가능
		
		P1 p1 = new P1();
		p1.m1();
		p1.m2();

	}

}

ex03-Tire,HanKook,Kumho,Car,Test

package ex03;

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;
		if(accumulatedRotation<maxRotation) {
			System.out.println(location + " Tire 수명: "+(maxRotation-accumulatedRotation)+"회");
			return true;
		}else {
			System.out.println("*** "+location+"Tire 펑크 ***");
			return false;
		}
	}
	
}

package ex03;

public class Car {
//필드	
	Tire frontLeftTire = new Tire("앞왼쪽", 6);  //매개변수2개인 생성자
	Tire frontRightTire = new Tire("앞오른쪽", 2);
	Tire backLeftTire = new Tire("뒤왼쪽", 3);
	Tire backRightTire = new Tire("뒤오른쪽", 4);
//생성자
	
//메소드
	int run() {
		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("[자동차가 멈춥니다.]");
	}
}

package ex03;

public class Hankook extends Tire {
	//필드
	//생성자
	public Hankook(String location,int maxRotation) {
		super(location, maxRotation);
	}
	//메소드

	@Override
	public boolean roll() {
		++accumulatedRotation;
		if(accumulatedRotation<maxRotation) {
			System.out.println(location + " Hankook 수명: "+(maxRotation-accumulatedRotation)+"회");
			return true;
		}else {
			System.out.println("*** "+location+"Hankook 펑크 ***");
			return false;
		}
		
	}	
}

package ex03;

public class Kumho extends Tire {
		//필드
		//생성자
		public Kumho(String location,int maxRotation) {
			super(location, maxRotation);
		}
		//메소드

		@Override
		public boolean roll() {
			++accumulatedRotation;
			if(accumulatedRotation<maxRotation) {
				System.out.println(location + " Kumho 수명: "+(maxRotation-accumulatedRotation)+"회");
				return true;
			}else {
				System.out.println("*** "+location+"Kumho 펑크 ***");
				return false;
			}
			
		}
	}

package ex03;

public class Test {

	public static void main(String[] args) {
		Car car = new Car(); 
		
		int problemLocation = 0;
		for(int i=1;i<=5;i++) {
			problemLocation = car.run();
		}
		
		switch(problemLocation) {
			case 1:
				System.out.println("앞왼쪽 Hankook로 교체");
				car.frontLeftTire = new Hankook("앞왼쪽", 15);
				break;
			case 2:
				System.out.println("앞오른쪽 Kumho로 교체");
				car.frontRightTire = new Kumho("앞오른쪽", 13);
				break;
			case 3:
				System.out.println("뒤왼쪽 Hankook로 교체");
				car.backLeftTire = new Hankook("뒤왼쪽", 14);
				break;
			case 4:
				System.out.println("뒤오른쪽 Kumho로 교체");
				car.backRightTire = new Kumho("뒤오른쪽", 17);
				break;
		
		}
		System.out.println("----------------------------------");

	}

}

ex04Student + Bus + Test  ~Page~345

package ex04;

public class Student {

	//필드
	String name; //학생이름
	int money;
	//생성자
	public Student(String name, int money) {
		this.name = name;
		this.money = money;
	}
	
	//메소드
	public void takeBus(Bus b) { //버스가 가진 b객체를 넘겼더니 다 사용할수있다.
		this.money -= b.bus_money;	 //버스비 지출	 
		b.take(money); //
	}
	
	public void takeSubway(Subway s) {
		//Subway 클래스타입으로 맨든 객체로전달받으려면 Subway(클래스명) 객체명 아무거나(s)로 받아야함
		this.money -= s.subway_money; //지하철 지출
		s.take(); // 지하철 탑승
	}
	
	public void takeTaxi(Taxi t,int m) { //택시번호 택시비
		this.money -= m;
		t.take(m);
	}

	@Override
	public String toString() {
		return "Student [name=" + name + ", money=" + money + "]";
	}	
}

package ex04;

public class Subway {
	
	int subwayNumber; //호선
	int passCount; //승객
	int money; //수입
	int subway_money = 1500; //요금
	
	public Subway(int subwayNumber) {
		this.subwayNumber = subwayNumber;
	}
	
	void take() {
		this.passCount += 1;
		this.money += subway_money;
	}

	@Override
	public String toString() {
		return "Subway [subwayNumber=" + subwayNumber + ", passCount=" + passCount + ", money=" + money
				+ ", subway_money=" + subway_money + "]";
	}
}

package ex04;

public class Subway {
	
	int subwayNumber; //호선
	int passCount; //승객
	int money; //수입
	int subway_money = 1500; //요금
	
	public Subway(int subwayNumber) {
		this.subwayNumber = subwayNumber;
	}
	
	void take() {
		this.passCount += 1;
		this.money += subway_money;
	}

	@Override
	public String toString() {
		return "Subway [subwayNumber=" + subwayNumber + ", passCount=" + passCount + ", money=" + money
				+ ", subway_money=" + subway_money + "]";
	}
}

package ex04;

import java.util.Scanner;

public class Test {
	public static void main(String[] args) {
		
		
		Scanner sc = new Scanner(System.in);
		
		
		Student su = new Student("성은",15000);
		Student yj = new Student("예진",12000);
		/*System.out.println(su.toString());
		System.out.println(yj.toString());
		
		Bus b148 = new Bus(148); //148버스생성
		su.takeBus(b148); //버스탄다
		System.out.println(b148.toString());
		
		System.out.println(su.toString());
		System.out.println(yj.toString());
		
		Bus b = new Bus();
		Bus b200 = new Bus(200); 
		su.takeBus(b200);
		yj.takeBus(b200);
		System.out.println(b200.toString());
		
		System.out.println(su.toString());
		System.out.println(yj.toString());
		
		Subway sub4 = new Subway(4);
		yj.takeSubway(sub4);
		System.out.println(sub4.toString());
		
		yj.takeSubway(sub4);
		System.out.println(sub4.toString());*/
		
		Taxi t1 = new Taxi("47나7293");
		System.out.print("택시를 몇분탔어 돈줘");
		int a =Integer.parseInt(sc.nextLine());
		t1.taxia(a);
		su.takeTaxi(t1, t1.taxia(a));
		System.out.println(su.toString());
		System.out.println(t1.toString());
		t1.taxis();
		/*
		System.out.print("너는 택시를 몇초탔어 돈줘");
		int c = Integer.parseInt(sc.nextLine());
		t1.taxia(c);
		System.out.println(t1.toString());
		t1.taxis();
		su.takeTaxi(t1, t1.taxia(c));*/
	
	}
}

 

 

 

ex05 Vehicle 부모  Driver Bus Taxi Test Page346~37 + Test2

package ex05;

public class Bus extends Vehicle {

	@Override
	public void run() {
		System.out.println("버스가 달린다.");
	}

	
}

package ex05;

public class Taxi extends Vehicle {

	@Override
	public void run() {
		System.out.println("택시가 달린다.");
		
	}
	
}

package ex05;

public class Vehicle {
	public void run() {
		System.out.println("차량이 달립니다.");
	}
}

package ex05;

public class Driver {
	public void drive(Vehicle v) {
		v.run();
	}
}

package ex05;

public class Test {

	public static void main(String[] args) {
		Driver d = new Driver();
		Bus b = new Bus();
		Taxi t = new Taxi();

		d.drive(b); //부모클래스타입으로 자식생성자를 받을수있어서
		d.drive(t);
	}
}

package ex05;

public class Test2 {

	public static void main(String[] args) {
		Test2 d = new Test2();
		Vehicle t = new Taxi();
		Vehicle b = new Bus();
		
		Taxi t1 = (Taxi)t;  //부모가 높기때문에 강제형변환으로 자식으로 만들어줘야 오류가 안뜸
		
		d.drive(t); // == d.drive(new Taxi());
		d.drive(b);
	}
	public void drive(Vehicle v) { //자
		v.run();
	}

}

 

 

 

댓글