본문 바로가기
코딩/수업 정리

20.12.10 Thu [014]

by 6^6 2020. 12. 10.
728x90
  • 상속 특징
  • 상속과 생성자
  • 클래스변수, 클래스메소드 상속

class Man {
	String name;

	public void tellYourName() {
		System.out.println("My name is " + name);

	}

}

class BusinessMan extends Man {
	String company;
	String position;

	public BusinessMan(String name, String company, String position) {
		this.name = name;
		this.company = company;
		this.position = position;
	}

	public void tellYourInfo() {

		System.out.println("My company is " + company);
		System.out.println("My position is " + position);
		tellYourName();
	}

}//코드 미완성

 

extends Man : Man을 확장한다. =상속(무엇을 상속? 클래스멤버랑 함수)

tellYourName

BusinessMan은 자식. Man은 부모. (상속되는 그림 BusinessMan(자식)Man(부모))

 

UML : 부모자식클래스를 도식화한것

 

 

상속과 생성자

↑부모클래스 바꾸면 큰일남.(왼쪽부분)

 

 

package java_1210;

public class SuperCLS {
	public SuperCLS() {
		System.out.println("I'm Super Class");
	}

}

class SubCLS extends SuperCLS {
	public SubCLS() {
		System.out.println("I'm Sub Class");
	}
}

class SuperSubCon {
	public static void main(String[] args) {
		new SubCLS(); //Heap에다가 객체만 생성하는거임
		//SibCLS subCLS = new SubCLS(); //이건 해당 하우스만들고 (주소만들고)객체생성
	}
}

 

 

**기본상식

this. 함수는? : 생성자호출.

 

 

 

 

 

jwdeveloper.tistory.com/8 

디폴트생성자 자세한설명

 

 

(JAVA) 디폴트 생성자(default constructor)

class Parent { private int money; private String name; public Parent(int money, String name) { this.money = money; this.name = name; } } class Child extends Parent{ public Child(int money, String n..

jwdeveloper.tistory.com

package java_1210; //코드 다시확인

class SuperCLS {
	public SuperSubCon() {
		System.out.println("I'm Super Class");
	}

}

class SubCLS extends SuperSubCon {
	public SubCLS() {
		System.out.println("I'm Sub Class");
	}
}

class SuperSubCon {
	public static void main(String[] args) {
		new SubCLS(); //Heap에다가 객체만 생성하는거임
		//SibCLS subCLS = new SubCLS(); //이건 해당 하우스만들고 (주소만들고)객체생성
	}
}
//I'm Sub Class

 

 

 

 

 

 

 

 

 

클래스변수, 클래스메소드 상속

package java_1210;

class SuperCLS {
	static int count = 0; //static붙었으니까 공유되는것.
						//어차피 부모클래스에있어서 공유됨.
						//but private주면 아무리 상속,부모클래스여도 X
	
	public SuperCLS() {
		count++;
	}
	
}
class SubCLS extends SuperCLS{
	public void showCount() {
		System.out.println(count);
	}
}
public class RecMain{
	public static void main(String[] args) {
		SuperCLS obj1 = new SuperCLS();
		SuperCLS obj2 = new SuperCLS();
		SubCLS obj3 = new SubCLS();
		obj3.showCount();
	}
}//3     (생성자 3개생성됐다는 뜻)

 

 

예제

1번

class TV{
   private int size;
   public TV(int size) { this.size = size; }
   protected int getSize() { return size; }
}

[1번] 다음 main() 메소드와 실행 결과를 참고하여 TV를 상속받은 ColorTV 클래스를 작성하라.

public static void main(String[] args) {
   ColorTV myTV = new ColorTV(32, 1024);
   myTV.printProperty();
}
===========
32인치 1024컬러
package java_1210;

class TV {

	private int size;

	public TV(int size) {
		this.size = size;
	}

	protected int getSize() {
		return size;
	}

}

class ColorTV extends TV {// TV에있는거 사용가능
	int color;

	public ColorTV(int size, int color) {
		super(size);// TV에서 상속받은거 호출
		this.color = color;

	}

	public void printProperty() {
		System.out.println(super.getSize() + "인치 " + color + "컬러");
			// 또는 getSize써도 됨,super.은 부모거 가져오겠다 라는 뜻.
	}
}

public class TVMain {

	public static void main(String[] args) {

		ColorTV myTV = new ColorTV(32, 1024);
		myTV.printProperty();

	}
}

2번

[2번] 다음 main() 메소드와 실행 결과를 참고하여 ColorTV를 상속받는 IPTV 클래스를 작성하라.

public static void main(String[] args) {
   IPTV iptv = new IPTV("192.1.1.2", 32, 2048); //"192.1.1.2" 주소에 32인치, 2048컬러
   iptv.printProperty();
}
=============================================
나의 IPTV는 192.1.1.2 주소의 32인치 2048컬러
package java_1210;

class ColorTV {

	private int size;

	public ColorTV(int size) {
		this.size = size;
	}

	protected int getSize() {
		return size;
	}
}

class IPTV extends ColorTV {
	private int color;
	private String address;

	public IPTV(String address, int size, int color) {
		super(size);
		this.color = color;
		this.address = address;
	}

	public void printProperty() {
		System.out.println("나의 IPTV는 " + address + " 주소에 " + super.getSize() + "인치, " + color + "컬러");
	}
}

public class TVMain {

	public static void main(String[] args) {
		IPTV iptv = new IPTV("192.1.1.2", 32, 2048);

		iptv.printProperty();

	}
}// "192.1.1.2" 주소에 32인치, 2048컬러

 

선생님답

package java_1210;

class ColorTV {

	private int size;
	private int color;

	public ColorTV(int size, int color) {
		this.size = size;
		this.color = color;
	}

	protected int getSize() {
		return size;

	}

	protected int getColor() {
		return color;
	}

	public void printProperty() {
		
		
	}
}

class IPTV extends ColorTV {
	private String address;

	public IPTV(String address, int size, int color) {

		super(size, color);
		this.address = address;
	}

	public void printProperty() {
		System.out.println("나의 IPTV는 " + address + " 주소에 " + super.getSize() + "인치, " + super.getColor() + "컬러");
		super.printProperty();
	}

}

public class TVMain {

	public static void main(String[] args) {
		IPTV iptv = new IPTV("192.1.1.2", 32, 2048);

		iptv.printProperty();

	}
}

 

 

 

zimt.tk/Wiederholung-8adb9628efda46b0adbb42c1d1ad6d8e

 

Wiederholung

https://zimt.tk/ Widerholung 페이지에는 2020.11.23 - 2021.05.06 기간 동안의 AiAcademy class4 수업 내용을 정리하고 있습니다.

www.notion.so

오늘의 문제

 

1.상속을 UML로 표기해 보세요.

BusinessMan(자식)Man(부모)


2.부모클래스와 자식클래스의 다른 용어들은?

상위클래스와 하위클래스 


3.super 키워드와 this 키워드의 차이는 무엇인가요?

this.데이터멤버 변수 접근할때 쓴다.

this()함수 -  자기 자신의 생성자호출,

super()함수 - 부모클래스 생성자 호출


4.단일 상속과 다중상속 이란?

단일상속은 부모클래스 1개만 상속받을 수 있고, 다중 상속은 여러개 받을 수 있다.

C++에선 다중 상속이 가능하다.


5.다음 코드와 같이 과목과 점수가 짝을 이루도록 2개의 배열을 작성하라.

 

String course[] = {"Java", "C++", "HTML5", "컴퓨터구조", "안드로이드"};
int score[]  = {95, 88, 76, 62, 55};
그리고 다음 예시와 같이 과목 이름을 입력받아 점수를 출력하는 프로그램을 작성하라. "그만"을 입력받으면 종료한다. (Java는 인덱스 0에 있으므로 score[0]을 출력)

과목 이름 >> Jaba
없는 과목입니다.
과목 이름 >> Java
Java의 점수는 95
과목 이름 >> 안드로이드
안드로이드의 점수는 55
과목 이름 >> 그만
[Hint] 문자열을 비교하기 위해서는 String 클래스의 equals()메소드를 이용해야 한다.

String name;
if(course[i].equals(name)) {
    int n = score[i];
    ...
}
package java_1210_prac;
 
import java.util.Scanner;
 
public class Score {
 
	private static int i;
	private static String name;
 
	public static void main(String[] args) {
 
		String course[] = { "Java", "C++", "HTML5", "컴퓨터구조", "안드로이드" };
		int score[] = { 95, 88, 76, 62, 55 };
		// System.out.print("과목 이름 >> ");
		Scanner sc = new Scanner(System.in);
 
		while (true) {
			System.out.print("과목 이름 >> ");
			String name = sc.nextLine();
			for (int i = course.length - 5; i < course.length; i++) {
				if (course[i].equals(name)) {
					int n = score[i];
					System.out.println(course[i]+"의 점수는 "+n+"점입니다");
 
				} else if (name.equals("그만")) {
					return;
				}
			}
			if (!course[i].equals(name) && !course[i].equals("그만")) {
				System.out.println("없는 과목입니다.");
				
			}
			
		}
 
	}
}//오류

 

 

 

6.다음은 2차원 상의 한 점을 표현하는 Point 클래스이다.

class Point {
   private int x, y;
   public Point(int x, int y) { this.x = x; this.y = y; }
   public int getX() { return x; }
   public int getY() { return y; }
   protected void move(int x, int y) { this.x =x; this.y = y; }
}


Point를 상속받아 색을 가진 점을 나타내는 ColorPoint 클래스를 작성하라. 다음 main() 메소드를 포함하고 실행 결과와 같이 출력되게 하라.

public static void main(String[] args) {
   ColorPoint cp = new ColorPoint(5, 5, "YELLOW");
   cp.setXY(10, 20);
   cp.setColor("RED");
   String str = cp.toString();
   System.out.println(str+"입니다. ");
}

=======================
RED색의 (10,20)의 점입니다.

 

package java_1210_prac;

class Point {
	private int x, y;
	public String color;

	public Point(int x, int y) {
		this.x = x;
		this.y = y;
	}

	public int getX() {
		return x;
	}

	public int getY() {
		return y;
	}

	protected void move(int x, int y) {
		this.x = x;
		this.y = y;
	}

	public void setXY(int x, int y) {
	}

	public void setColor(String string) {
	}

	public String toString() {
		System.out.println(color + "색의 (" + getX() + ", " + getY() + ")의 점입니다.");

		return "";
	}

}

class ColorPoint extends Point {

	public ColorPoint(int x, int y, String color) {
		super(x, y);
		this.color = color;
	}

}

public class PointMain {
	public static void main(String[] args) {

		ColorPoint cp = new ColorPoint(5, 5, "YELLOW");
		cp.setXY(10, 20);
		cp.setColor("RED");
		String str = cp.toString();
		
	}
}

↑오류. ↓오류해결. set 함수 두개를 toString에 넣고 각각 red 10,20 이 나오게 내용에 적어줌.

package java_1210_prac;

class Point {
	protected int x;
	protected int y;
	public String color;

	public Point(int x, int y) {
		this.x = x;
		this.y = y;
	}

	public int getX() {
		return x;
	}

	public int getY() {
		return y;
	}

	protected void move(int x, int y) {
		this.x = x;
		this.y = y;
	}

	public String toString() {
		System.out.println(color + "색의 (" + this.x + ", " + this.y + ")의 점입니다.");

		return "";
	}

}

class ColorPoint extends Point {

	public ColorPoint(int x, int y, String color) {
		super(x, y);
		this.color = color;

	}

	public void setXY(int x, int y) {
		this.x = x;
		this.y = y;

	}

	public void setColor(String color) {

		this.color = color;

	}

}

public class PointMain {
	public static void main(String[] args) {

		ColorPoint cp = new ColorPoint(5, 5, "YELLOW");
		cp.setXY(10, 20);
		cp.setColor("RED");
		String str = cp.toString();

	}
}

제대로된 풀이↓

 

class Point {
	private int x, y;

	public Point(int x, int y) {
		this.x = x;
		this.y = y;
	}

	public int getX() {
		return x;
	}

	public int getY() {
		return y;
	}

	protected void move(int x, int y) {
		this.x = x;
		this.y = y;
	}
}

class ColorPoint extends Point {
	private String color;

	public ColorPoint(int x, int y, String color) {
		super(x, y);
		this.color = color;
	}
	public String getColor() {
		return color;
	}

	public void setXY(int x, int y) {
		move(x,y);
	}

	public void setColor(String color) {

		this.color=color;
	}

	public String toString() {

		return this.color + "색의 (" + getX() + "," + getY() + ")의 점";

		

	}

}

public class PointMain {

	public static void main(String[] args) {
		ColorPoint cp = new ColorPoint(5, 5, "YELLOW");
		cp.setXY(10, 20);
		cp.setColor("RED");
		String str = cp.toString();
		System.out.println(str + "입니다. ");
	}
}

 

 

7.Point를 상속받아 색을 가진 점을 나타내는 ColorPoint 클래스를 작성하라. 다음 main() 메소드를 포함하고 실행 결과와 같이 출력되게 하라.

public static void main(String[] args) {
   ColorPoint zeroPoint = new ColorPoint(); // (0,0) 위치의 BLACK 색 점
   System.out.println(zeroPoint.toString() + "입니다.");
   ColorPoint cp = new ColorPoint(10, 10); // (10,10) 위치의 BLACK 색 점
   cp.setXY(5,5);
   cp.setColor("RED");
   System.out.println(cp.toString()+"입니다.");
}
=========================
BLACK색의 (0,0) 점입니다.
RED색의 (5,5) 점입니다.
package java_1210_prac;//미완성

class Point {
	private int x, y;
	public String color;

	public Point(int x, int y) {
		this.x = x;
		this.y = y;
	}

	public int getX() {
		return x;
	}

	public int getY() {
		return y;
	}

	protected void move(int x, int y) {
		this.x = x;
		this.y = y;
	}

	public void setXY(int x, int y) {
	}

	public void setColor(String string) {
	}

	public String toString() {
		System.out.println(color+ "색의 (" + this.x + ", " + this.y + ")의 점입니다.");

		return "";
	}

}

class ColorPoint extends Point {

	public ColorPoint() {
		super(x, y);
		this.color = color;
	}

	public ColorPoint(int x, int y) {
		// TODO Auto-generated constructor stub
	}

}

public class PointMain2 {
	ppublic static void main(String[] args) {
		   ColorPoint zeroPoint = new ColorPoint(); // (0,0) 위치의 BLACK 색 점
		   System.out.println(zeroPoint.toString() + "입니다.");
		   ColorPoint cp = new ColorPoint(10, 10); // (10,10) 위치의 BLACK 색 점
		   cp.setXY(5,5);
		   cp.setColor("RED");
		   System.out.println(cp.toString()+"입니다.");
		}
		=========================
		BLACK색의 (0,0) 점입니다.
		RED색의 (5,5) 점입니다.
		
	}
}

 

 

 

8.Point를 상속받아 3차원의 점을 나타내는 Point3D 클래스를 작성하라. 다음 main() 메소드를 포함하고 실행 결과와 같이 출력되게 하라.

public static void main(String[] args) {
   Point3D p = new Point3D(1,2,3); // 1,2,3은 각각 x, y, z축의 값.
   System.out.println(p.toString()+"입니다.");
   p.moveUp(); // z 축으로 위쪽 이동
   System.out.println(p.toString()+"입니다.");
   p.moveDown(); // z 축으로 아래쪽 이동
   p.move(10, 10); // x, y 축으로 이동
   System.out.println(p.toString()+"입니다.");
   p.move(100,  200, 300); // x, y, z축으로 이동
   System.out.println(p.toString()+"입니다.");
}
(1,2,3) 의 점입니다.
(1,2,4) 의 점입니다.
(10,10,3) 의 점입니다.
(100,200,300) 의 점입니다.

9.배열을 이용하여 간단한 극장 예약 시스템을 작성하여 보자.

아주 작은 극장이라서 좌석이 10개 밖에 되지 않는다.

사용자가 예약을 하려고 하면 먼저 좌석 배치표를 보여준다.

즉, 예약이 끝난 좌석은 1로, 예약이 되지 않은 좌석은 0으로 나타낸다.

=========
출력
--------------------
0 1 2 3 4 5 6 7 8 9
--------------------
0 0 0 0 0 0 0 0 0 0

몇번째 좌석을 예약 하시겠습니까? 2
--------------------
0 1 2 3 4 5 6 7 8 9
--------------------
0 0 1 0 0 0 0 0 0 0

클래스 나누기 전↓

//SeatsArr.java
import java.util.Scanner;

public class SeatsArr {

	public static void main(String[] args) {
		int[] arr = new int[10];
		
		Scanner sc = new Scanner(System.in);
		
		for(int i = 0; i<arr.length; i++) {
			System.out.print(i + " ");
		}
		System.out.println();
		
		for(int i = 0; i<arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
		System.out.println();
		
		System.out.print("몇 번째 좌석을 예약 하시겠습니까? ");
		int seat = sc.nextInt();
		
		for(int i = 0; i<arr.length; i++) {
			if(seat == i) {
				arr[i] = 1;
			}
		}
		
		for(int i = 0; i<arr.length; i++) {
			System.out.print(i + " ");
		}
		System.out.println();
		
		for(int i = 0; i<arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
		System.out.println();
		
	}

}

클래스 나눈 후↓

 

//SeatsArr.java
public class SeatsArr {

	public static void main(String[] args) {

		Reservation myRes = new Reservation();  //객체생성
		myRes.reserveSeat();                   //좌석 예약 함수실행 (캡슐화)
	}
}
//Reservation.java

import java.util.Scanner;

class Reservation {
	private int[] arr = new int[10];
	
	Scanner sc = new Scanner(System.in);
	
	private void showSeats() {
		for(int i = 0; i<arr.length; i++) {  //좌석 배열 번호 출력
			System.out.print(i + " ");
		}
		System.out.println();
		
		for(int i = 0; i<arr.length; i++) {  //좌석 배열 값 출력
			System.out.print(arr[i] + " ");
		}
		System.out.println();
	}
	
	private void chooseSeat() {
		System.out.print("몇 번째 좌석을 예약 하시겠습니까? "); //입력받기
		int seat = sc.nextInt();
		
		for(int i = 0; i<arr.length; i++) {  //입력받은 좌석에 1 넣기
			if(seat == i) {
				arr[i] = 1;
			}
		}
	}
	
	public void reserveSeat () {  //encapsulation
		showSeats();
		chooseSeat();
		showSeats();
	}
}
728x90

'코딩 > 수업 정리' 카테고리의 다른 글

질문,헷갈리는 거 정리  (0) 2020.12.13
20.12.11 Fri [015]  (0) 2020.12.11
20.12.09 Wed [013]  (0) 2020.12.09
20.12.08 Tue [012]  (0) 2020.12.08
20.12.07 Mon [011]  (0) 2020.12.07

댓글