** 예제 1117 (생성자) **

class Document{
	
	static int count = 0;
	String name;
	
	Document(){
		this("제목없음" + (++count));
	}
	
	Document(String name){
		this.name = name;
		System.out.println("문서 " + name + "이 생성되었습니다.");
	}
}

public class MySample1117 {

	public static void main(String[] args) {
		
		//생성자
		Document d1 = new Document();
		Document d2 = new Document("자바.txt");
		Document d3 = new Document();
		Document d4 = new Document();

	}

}

 

* 결과

문서 제목없음1이 생성되었습니다.
문서 자바.txt이 생성되었습니다.
문서 제목없음2이 생성되었습니다.
문서 제목없음3이 생성되었습니다.




** 상속(inheritance) **

- 기존의 클래스를 재사용하여 새로운 클래스를 작성하는 것

- 상속을 통해 부모의 클래스가 가지고 있는 모든 것을 (생성자 제외) 자식클래스가 물려받아 같이 공유하고 확장하는 기념

// new 객체가 만들어진 순간에는 호출되지만, 생성자를 물려받아 공유할 수는 없다.

- 예) class Child extends Parent {

        

        }

// extends 다음에 부모클래스는 한개만 쓸수 있다.

조상클래스 : 부모(Parent)클래스, 상위(super)클래스, 기반(base)클래스

자손클래스 : 자식(chlid)클래스, 하위(sub)클래스, 파생된(derived)클래스

 

- 예) class Parent(

                  int age;

         }

       

        class Child extends Parent {

        

        }


** 예제 1117_2 (상속) **

class Tv2{
	boolean power;		//전원상태(on/off)
	int channel;
	
	Tv2(){
		channel = 11;
		System.out.println("Tv2() 생성자...");
	}
	
	void power() {
		power = !power;
	}
	
	void channelUp() {		//부모변수가 증가함.
		++channel;
	}
	
	void channelDown() {
		--channel;
	}
}


class CaptionTv extends Tv2{
	
	boolean caption;		//자막상태
	int channel;
	
	CaptionTv(){			//생성자에서 부모가 호출된다.
//		super();			//생략되어있음. 무조건 첫번째줄에 와야함. super를 부르기때문에 부모 먼저 호출됨
		channel = 20;
		System.out.println("CaptionTv() 생성자...");
	}
	
	void displayCaption(String text) {
		int channel = 30;
		
		if(caption) {		//this.caption 에 this가 생략됨(지역변수 cation이 없기 때문)
			System.out.println("자막내용 : " + text);
		}
		
		System.out.println("부모 channel : " + super.channel);	//상속관계에서 부모인스턴스 지칭하는것 : super
		System.out.println("인스턴스 : " + this.channel);			//내 클래스의 인스턴스 지칭 : this
		System.out.println("channel : " + channel);
		//지역변수 인스턴스변수 부모변수 불러보기
	}
	
	int getChannel() {				//
		return super.channel;		//인스턴스변수(지역변수가 있을 시) : this.channel | 부모변수 : super.channel
	}
	
	
}

//변수값 찾을 때 지역변수 ->  자식인스턴스변수 -> 부모변수 순서로 찾는다. (cf : 메인메소드에서 channel찍으면 인스턴스 자식도있고 부모도있으)

public class MySample1117_2 {

	public static void main(String[] args) {
		
		//상속
		CaptionTv ctv = new CaptionTv();	//자식클래스 인스턴스ctv에 CaptionTv 객체 생성
		System.out.println("channel : " + ctv.channel);
		ctv.channel = 10;		//인스턴스변수에 10 대입.
		ctv.channelUp();
		System.out.println("channel : " + ctv.channel);
		ctv.displayCaption("Hello JAVA...");		//caption 디폴트값이 false라 출력 안됨.
		ctv.caption = true;
		ctv.displayCaption("Hello JAVA");
		ctv.power();								//없으면 아래 ctv.power가 false로 출력됨
		System.out.println("ctv.power : " + ctv.power);
		System.out.println("ctv.getChannel : " + ctv.getChannel());
		
	}

}

 

* 출력

Tv2() 생성자...
CaptionTv() 생성자...
channel : 20
channel : 10
부모 channel : 12
인스턴스 : 10
channel : 30
자막내용 : Hello JAVA
부모 channel : 12
인스턴스 : 10
channel : 30
ctv.power : false
ctv.getChannel : 12

 

// staic int channel이 아니지만 12 가 출력되는 이유 

 - ctv.channelUp();을 실행한후 값 유지 (이유 - ctv라는 동일한 인스턴스 객체이기때문 )


** 예제 1117_3 (상속) **

class Person{
	void breath() {
		System.out.println("숨쉬기");
	}
	
	void eat() {
		System.out.println("밥먹기");
	}
	
	void say() {
		System.out.println("말하기");
	}
}

class Student extends Person{
	void learn() {
		System.out.println("공부하기...");
	}
}

class Teacher extends Person{
	void teach() {
		System.out.println("설명하기...");
	}
}


public class MySample1117_3 {

	public static void main(String[] args) {
		
		//상속_2번 받는 경우
		
		Student s1 = new Student();
		s1.breath();
		s1.learn();
		
		Teacher t1 = new Teacher();
		t1.eat();
		t1.breath();
		t1.teach();
		
	}

}

** 예제 1117_4 (상속) **

class Point{		//x, y좌표값만
	int x;
	int y;
	
	Point(){
		this(0, 0);
	}
	
	Point(int x, int y){
		this.x = x;
		this.y = y;
	}
	
	String getXY() {
		return "(" + x + ", " + y + ")";	//문자열 형태로 보내주기 위해 만듬
	}
	
}

class Shape{		//색가지고 그리기만
	String color = "black";
	
	void draw() {
		System.out.printf("[color = %s] \n", color);
	}
}

class Circle extends Shape{
	Point center;		//??
	int r;
	
	Circle(){
		//Point p = new Point(0, 0);
		//this(p, 100);			//this() 는 항상 첫번째 라인에서 호출되어야 함.
		this(new Point(0, 0), 100);	//new Point(0, 0) -> new 객체생성한 주소값 반환
	}
	
	Circle(Point center, int r){
		this.center = center;
		this.r = r;
	}
	
	void draw() {
		System.out.printf("[center=(%d, %d), r=%d, color=%s]\n", center.x, center.y, r, color);
	}
}

class Triangle extends Shape{
	Point[] p = new Point[3];	// 좌표를 배열로 3개 생성함
	
//	Triangle() {
//		
//	}	//메인에서 new Triangle 객체생성할 때 오류안나기 위해 만들어준다.
		// 컬파일러 jdk가 생성자 만들어줌 - > 모든 클래스는 생성자가 하나 존재한다.
		// jdk는 생성자가 하나라도 존재하면 빈생성자 만들어주기 않기때문에 -> 빈생성자 하나 만들어 줘야한다.
	
	Triangle(Point[] p) {		//Point[] 클래스 배열타입을 받겠다는 의미.
		System.out.println("before : " + this.p.length);
		this.p = p;
		System.out.println("after : " + this.p.length);
	}
	
	void draw() {
		System.out.printf("[p1=%s, p2=%s, p3=%s, color=%s] \n", p[0].getXY(), p[1].getXY(), p[2].getXY(), color);
	}
}

public class MySample1117_4 {

	public static void main(String[] args) {
		
		//상속_도형그리기
		
		Point[] p = {
						new Point(100, 100),	//시작 주소값 넘겨줌
						new Point(140, 50),
						new Point(200, 100)
					};
		
		Triangle t = new Triangle(p);
		Circle c = new Circle(new Point(150, 150), 50);
		
		//바로 위 선을 분리하여 적용시 (더 직관적이지만 p2메모리가 더 할당되야한다.)
		//Point p2 = new Point(150, 150);
		//Circle c = new Circle(p2, 50);
		
		t.draw();	//삼각형 그리기
		c.draw();	//원그리기	

	}

}

** 예제 1117_5 **

class Person2{
	String name;
	String job;
	int age;
	
	Person2(String name, String job, int age){
		this.name = name;
		this.job = job;
		this.age = age;
	}
}

class Student2 extends Person2{	//생성자 때문에 오류남
	
	int score;
	
	Student2(String name, String job, int score, int age){
		
//		super.name = name;
//		super.job = job;
//		super.age = age;
		super(name, job, age);
		
		this.score = score;	
	}
	
	void print() {
//		System.out.println("이름 : " + super.name + ", 직업 : " +  super.job + ", 나이" + super.age + ", 점수" + this.score);
		System.out.println("이름 : " + name + ", 직업 : " +  job + ", 나이 : " + age + ", 점수 : " + score);
	}
}

class Teacher2 extends Person2{
	int pay;
	
	Teacher2(String name, String job, int age, int pay){
//		super.name = name;
//		super.job = job;
//		super.age = age;
		super(name, job, age);	//자식클래스에서 부모클래스의 변수에 값을 넣을때는 부모클래스의 생성자 이용하는 것이 좋다.
		this.pay = pay;
	}
	
	void print() {
//		System.out.println("이름 : " + super.name + ", 직업" + super.job + ", 나이" + super.age + ", 급여" + this.pay);	//올바른 문법
		System.out.println("이름 : " + name + ", 직업 : " + job + ", 나이 : " + age + ", 급여 : " + pay);
	}
}



public class Sample1117_5 {

	public static void main(String[] args) {
		// 상속
		
		Student2 s1 = new Student2("홍길동", "학생회장", 100, 19);
		s1.print();
		
		Teacher2 t1 = new Teacher2("펭수", "본부장", 40, 1000);
		t1.print();

	}

}

 

// s1이 바라보는 Person2와 t1이 바라보는 Person2는 다르다.

// super() -> 부모 생성자

// super.~~ -> 부모 인스턴스


** 실습 1117_6 **

/* 1
 부모클래스틑 Animal 클래의 멤버변수는 이름, 이동수단, 울음소리, 다리수로 정의
 각 멤버변수를 제어하는 메서드도 포함(get, set메서드를 활용하여 변수값 활용)
 단, get으로 시작하는 메서드는 해당 클래스에 인스턴스변수 값을 보내주는 것이며,
  set으로 시작하는 메서드는 해당 클래스에 인스턴스 변수에 값으르 저장하는 것임
 Animal 클래스를 상속받은 자식 클래스를 만들어서 각각의 이름, 이동수단, 울음소리, 다리수를 출력하는 프로그램.
 클래스는 Dog(강아지), Eagle(독수리), Lion(사자), Cat(고양이)
 출력은 name(이름), move(이동수단), cry(울음소리), leg(다리수)
 출력예)강아지 이름은 해피이고, 이동방법은 껑충껑충, 울음소리는 멍멍, 다리수는 4입니다.
    독수리 이름은 이글이고, 이동방법은 펄럭펄럭, 울음소리는 구구, 다린수는 2입니다.
    사자 이름은 어흥이고, 이동방법은 휙휙휙, 울음소리는 어흥어흥, 다리수는 4 입니다.
    고양이 이름은 나비이고, 이동방범은 껑충껑충, 울음소리는 야옹야옹, 다리수는 4입니다.
 단, 출력은 메인메서드에서 실행
 */

class Animal{
	
	
	String name;
	String move;
	String cry;
	int leg;
	
	Animal(){
		
	}
	
	Animal(String name, String move, String cry, int leg){
		this.name = name;
		this.move = move;
		this.cry = cry;
		this.leg = leg;
		
	}
	
	void setName(String name){		//set과 get은 세트로 잘 다닌다. set에서 값을 세팅하고 get에서 return반환값을 보낸다.
		this.name = name;
	}
	String getName(){
		return this.name;
	}
	
	void setMove(String move){
		this.move = move;
	}
	String getMove(){
		return this.move;
	}
	
	void setCry(String cry) {
		this.cry = cry;
	}
	String getCry() {
		return cry;
	}
	
	void setLeg(int leg) {
		this.leg = leg;
	}
	int getLeg() {
		return leg;
	}
	
}

class Dog extends Animal{
	Dog(String name, String move, String cry, int leg){
		super(name, move, cry, leg);
	}
}

class Eagle extends Animal{
	Eagle(String name, String move, String cry, int leg){
		super(name, move, cry, leg);
	}
}

class Lion extends Animal{
	Lion(String name, String move, String cry, int leg){
		super(name, move, cry, leg);
	}
}

class Cat extends Animal{
	Cat(String name, String move, String cry, int leg){
		super(name, move, cry, leg);
	}
}


public class MySample1117_6 {

	public static void main(String[] args) {
		//상속
		
		Animal a = new Animal();
		Dog d = new Dog("해피", "껑충껑충", "멍멍", 4);
		Eagle e = new Eagle("이글", "펄럭펄럭", "구구", 2);
		Lion l = new Lion("어흥", "휙휙휙", "어흥어흥", 4);
		Cat c = new Cat("나비", "껑충껑충", "야옹야옹", 4);
		
		System.out.println("강아지 이름은 " + d.getName() + "이고, 이동방법은 " + d.getMove() + ", 울음소리는 " + d.getCry() + ", 다리수는 " + d.getLeg() + "입니다.");
		System.out.println("독수리 이름은 " + e.getName() + "이고, 이동방법은 " + e.getMove() + ", 울음소리는 " + e.getCry() + ", 다리수는 " + e.getLeg() + "입니다.");
		System.out.println("사자 이름은 " + l.getName() + "이고, 이동방법은 " + l.getMove() + ", 울음소리는 " + l.getCry() + ", 다리수는 " + l.getLeg() + "입니다.");
		System.out.println("고양이 이름은 " + c.getName() + "이고, 이동방법은 " + c.getMove() + ", 울음소리는 " + c.getCry() + ", 다리수는 " + c.getLeg() + "입니다.");
		

	}

}

 


** 선생님 풀이 1117_6 (상속) **

// MySample1117_6의 문제를 선생님 방법

class Animal2{
	String name;	//이름
	String move;	//이동수단
	String cry;		//울음소리
	int leg;		//다리수
	
	Animal2(){
		this("","","",0);
	}
	
	Animal2(String name, String move, String cry, int leg){
//		this.name = name;	//이름
//		this.move = move;	//이동수단
//		this.cry = cry;		//울음소리
//		this.leg = leg;
		
		//위 주석과 동일한 의미
		setName(name);
		setMove(move);
		setCry(cry);
		setLeg(leg);
	}

	
	String getName() {
		return this.name;
	}
	
	void setName(String name) {
		this.name = name;
	}
	
	String getMove() {
		return this.move;
	}
	
	void setMove(String move) {
		this.move = move;
	}
	
	String getCry() {
		return this.cry;
	}
	
	void setCry(String cry) {
		this.cry = cry;
	}
	
	int getLeg() {
		return this.leg;
	}
	
	void setLeg(int leg) {
		this.leg = leg;
	}

	
	
}

//-Animal 과 Animal을 상속받는 클래스들에 아무것도 없을때 오류가 안나는 이유 - 생성자 하나도 없으면 jdk에서 빈 생성자를 각각 하나씩 만들어주기 때문에
class Dog2 extends Animal{		
	Dog2(){
		this("","","",0);		//현단계에서 super(); 호출 하지 않게 하는 방법중 하나.
	}
	
	Dog2(String name, String move, String cry, int leg){
		super(name, move, cry, leg);
	}
}

class Eagle2 extends Animal{
	Eagle2(){
		
	}
	Eagle2(String name, String move, String cry, int leg){
		super(name, move, cry, leg);
	}
}

class Lion2 extends Animal{
	Lion2(){
		
	}
	Lion2(String name, String move, String cry, int leg){
		super(name, move, cry, leg);
	}
	
}

class Cat2 extends Animal{
	Cat2(){
		
	}
	Cat2(String name, String move, String cry, int leg){
		super(name, move, cry, leg);
	}
	
}


public class MySample1117_7 {

	public static void main(String[] args) {
		
		//상속
		//강아지 이름은 해피이고, 이동방법은 껑충껑충, 울음소리는 멍멍, 다리수는 4입니다.
		
		Dog2 d = new Dog2("해피","껑충껑충","멍멍",4);
		System.out.println("강아지 이름은 " + d.getName() + "이고, 이동방법은 " + d.getMove() + ", 울음소리는 " + d.getCry() + ", 다리수는 " + d.getLeg() + "입니다.");
		
		Eagle2 e = new Eagle2("이글", "펄럭펄럭", "구구", 2);
		System.out.println("독수리 이름은 " + e.getName() + "이고, 이동방법은 " + e.getMove() + ", 울음소리는 " + e.getCry() + ", 다리수는 " + e.getLeg() + "입니다.");
		
		Lion2 l = new Lion2("어흥이", "휙휙", "어흥어흥", 4);
		System.out.println("사자 이름은 " + l.getName() + "이고, 이동방법은 " + l.getMove() + ", 울음소리는 " + l.getCry() + ", 다리수는 " + l.getLeg() + "입니다.");
		
		Cat2 c = new Cat2("나비", "껑충꺼충", "야옹야옹", 4);
		System.out.println("고양이 이름은 " + c.getName() + "이고, 이동방법은 " + c.getMove() + ", 울음소리는 " + c.getCry() + ", 다리수는 " + c.getLeg() + "입니다.");
		
	}

}

 

 

 

 

// Generate 실행 예
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

+ Recent posts