본문 바로가기
Language/JAVA

JAVA 6일차 - toString 메소드, 상속 예제 연습

by 코젼 2022. 6. 27.
728x90
반응형

📃상속 예제(1) - Car

//클래스명 : Car
//멤버변수 : 데이터타입-변수명-용도
// int-door-문의개수, String-color-차의색상, String-gearType-기어타입
//생성자
// 매개변수를 3개 갖는 생성자 - 문의개수,색상, 기어타입을 전달받아 멤버변수 초기화
// 기본생성자 - 문의갯수는 3, 색상은 white, 기어타입은 auto로 멤버변수 초기화
//메서드 
//toStirng()을 오버라이드 - 모든 멤버 변수를 문자열로 반환
//테스트 코드 : 문의 갯수와 색상, 기어타입이 다음과 같은
//            2개의 Car 인스턴스를 생성하고 정보를 출력
//            1번 인스턴스 - 3, white, auto
//            2번 인스턴스 - 4, red, auto

public class Car {
	
	public static void main(String[] args) {
		CarSmart c1 = new CarSmart();
		CarSmart c2 = new CarSmart(4, "red", "auto", true);
		
		System.out.println(c1);
		System.out.println(c2);
	}
	
	int door;
	String color;
	String gearType;
	
	Car(int door, String color, String gearType) {
		this.door = door;
		this.color = color;
		this.gearType = gearType;
	}
	
	Car() {
		this(3, "white", "auto");
	}
	
	@Override
	public String toString() {
		return door + ", " + color + ", " + gearType;
	}
	
}


//클래스명 : CarSmart
//조상클래스 : Car
//멤버변수 : 데이터타입-변수명-용도
//boolean - autoMode - 자동 운전 여부
//생성자
//매개변수를 4개 갖는 생성자 - 문의개수, 색상, 기어타입, 자동운전 모드를 전달받아 멤버변수 초기화
//기본 생성자 - 문의 갯수는 3, 색상은 white, 기어타입은 auto, 자동운먼모드는 false로 초기화
//매서드
//toAutoMode - 반환타입 boolean -> 자동운전모드 여부를 잔환 - 전달인자 없음
//toString()을 오버라이드 - 모든 멤버 변수를 문자열을 반환
class CarSmart extends Car{
	boolean autoMode;
	
	CarSmart(int door, String color, String gearType, boolean autoMode) {
		super(door, color, gearType);
		this.autoMode = autoMode;
	}
	
	CarSmart() {
		this(3, "white", "auto", false);
	}
	
	boolean toAutoMode() {
		return this.autoMode;
	}
	
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		String str = (autoMode) ? "자동운전모드" : "수동운전모드";
		return super.toString() + ", " + str;
	}
}

📃상속 예제(2) - Card

//클래스명 : Card
//멤버변수 : 데이터타입-변수명-용도
//         String-shape-카드의무늬 
//		   int-num-카드의 숫자
//		   int-height-카드의 세로길이 
//		   int-width-카드의 가로길이 
//생성자
//매개변수가 4개인 생성자 : 카드의 무늬와 숫자, 가로 세로 길이를 전달받아 
//                     멤버변수를 초기화
//매개변수가 2개인 생성자 : 카드의 무늬와 숫자를 전달받아 멤버변수를 초기화하고
//                     가로와 세로 길이를 각각 100과 200으로 초기화
//메서드 
//toString을 오버라이딩하여 무늬와 숫자, 가로 세로 길이를 출력
//테스트 코드 : 길이가 5인 Card 타입의 배열에 난수로 초기화한 카드의 인스턴스를 저장하고 정보를 출력
//            무늬는 diamond, heart, spade, clover 중 하나
//            숫자는 1부터 13 사이의 값 중 하나
public class Card {
	public static void main(String[] args) {
		Card[] c = new Card[5];
		String shape[] = { "diamond", "heart", "spade", "clover" };

		int num = 0;
		int index = 0;

		for (int i = 0; i < c.length; i++) {
			num = (int) (Math.random() * 13) + 1;
			index = (int) (Math.random() * 3);
			
			c[i] = new Card(shape[index], num);
			
			System.out.println(c[i]);
		}
	}

	String shape;
	int num;
	int height;
	int width;

	Card(String shape, int num, int height, int width) {
		this.shape = shape;
		this.num = num;
		this.height = height;
		this.width = width;
	}

	Card(String shape, int num) {
		this.shape = shape;
		this.num = num;
		this.height = 100;
		this.width = 200;
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return shape + ", " + num;
	}
}

📃상속 예제(3) - Student

//클래스명 : StudentEx
//조상클래스명 : Student
//멤버변수 : 데이터타입-변수명-용도
//         int -java - 자바 파일명
//생성자
//매개변수가 3개인 생성자 - 이름, 반, 번호를 전달받아 초기화, 모든 점수는 -1로 초기화
//매개변수가 7개인 생성자 - 이름, 반, 번호, 국영수, 자바 점수를 전달받아 멤버변수를 초기화
//메서드 : 메서드명-반환타입-기능-전달인자
//setJava - void-자바점수설정-자바점수
//getJava - int - 자바점수를 반환, 전달인자 없음
//getTotal-int-국영수와 자바 총점을 반환, 점수가 입력되기 전이면 오류 메세지
//toString 오버라이딩 - 모든 멤버변수들을 출력
//getAverage-float-국영수자바의 평균을 반환

class StudentEx extends Student {
	int java;

	StudentEx(String name, int ban, int no) {
		super(name, ban, no, -1, -1, -1);
	}
	
	StudentEx(String name, int ban, int no, int kor, int eng, int math, int java) {
		super(name, ban, no, kor, eng, math);
		this.java = java;
	}
	
	void setJava(int java) {
		this.java = java;
	}
	
	int getJava() {
		return this.java;
	}
	
	int getTotal(int kor, int eng, int math, int java) {
		if(kor < 0 || eng < 0 || math < 0 || java < 0) {
			System.out.println("오류");
		}
		return super.getTotal(kor, eng, math) + this.java;
	}
	
	
	@Override
	public String toString() {
		return super.toString() + this.java + ", " + this.getTotal(kor, eng, math, java);
	}
	
	
}



//클래스명 : Student
//멤버변수 : 데이터타입-변수명-용도
//			String-name-이름
//			int-ban-반
//			int-no-번호
//			int-kor-국어점수
//			int-eng-영어점수
//			int-math-수학점수
//생성자
//매개변수가 3개인 생성자 - 이름, 반, 번호를 전달받아 초기화, 모든 점수는 -1로 초기화
//매개변수가 6개인 생성자 - 이름, 반, 번호, 국영수 점수를 전달받아 멤버변수를 초기화
//메서드 : 메서드명-반환타입-기능-전달인자
//setKor-void-국어점수설정-국어점수
//setEng-void-영어점수설정-영어점수
//setMath-void-수학점수설정-수학점수
//getKor, getEng, getMath - 각각 국영수 점수를 반환, 반환타입 int, 전달인자 없음
//getTotal-int-국영수 총점을 반환, 점수가 입력되기 전이면 오류 메세지
//toString 오버라이딩 - 모든 멤버변수들을 출력
//getAverage-float-국영수 평균을 반환
public class Student {
	
	public static void main(String[] args) {
		// TODO main
		StudentEx s = new StudentEx("홍길동", 1, 15, 100, 80, 90, 100);
		System.out.println(s);
	}
	String name;
	int ban;
	int no;
	int kor;
	int eng;
	int math;
	
	
	Student(String name, int ban, int no) {
		this(name, ban, no, -1, -1, -1);
	}
	
	Student(String name, int ban, int no, int kor, int eng, int math) {
		// 여기서 사용되는 this는 84번째 줄에 있는 Student 생성자를 호출하는 것이다.
		this.name = name;
		this.ban = ban;
		this.no = no;
		this.kor = kor;
		this.eng = eng;
		this.math = math;
	}
	
	int getTotal(int kor, int eng, int math) {
		int sum = (kor + eng + math);
		
		if(this.kor < 0 || this.eng < 0 || this.math < 0) {
			System.out.println("오류");
		}
		
		return sum;
	}
	
	@Override
	public String toString() {
		return name + ", " + ban + ", " + no + ", " + kor + ", " + eng + ", " + math + ", ";
	}
	
	void setKor(int kor) {
		this.kor = kor;
	}
	
	void setEng(int eng) {
		this.eng = eng;
	}
	
	void setMath(int math) {
		this.math = math;
	}
	
	int getKor() {
		return this.kor;
	}
	
	int getEng() {
		return this.eng;
	}
	
	int getMath() {
		return this.math;
	}
}

📃상속 예제(4)

public class superExample {
		public static void main(String[] args) {
			Child c = new Child();
			c.method();
	}
	
}

class Parent {
	int x = 10;
}

class Child extends Parent {
	
		void method() {
			int x = 20;
			System.out.println("x = " + x);
			System.out.println("this.x = " + this.x);
			System.out.println("super.x = " + super.x);
		}
}

📃상속 예제(5) - Point

//클래스명 : Point
//멤버변수 : 데이터타입-변수명-용도
// int - x - x좌표
// int - y - y좌표
//생성자
// 매개변수가 2개인 생성자 - x, y 좌표를 전달받아 멤버변수에 저장
//메서드 : 메서드명-반환타입-기능-전달인자
// getLocation - String - xy 좌표값을 문자열로 반환 - 없음
//테스트 코드 : x,y좌표가 10, 20인 Point 인스턴스를 생성하고 화면에 좌표값을 출력

public class TestMain {
	public static void main(String[] args) {
		Point3D p = new Point3D(10, 20, 30);
		System.out.println(p.getLocation());
	}
}

class Point {
	
	int x;
	int y;
	
	// super(); 를 사용하려면 기본생성자를 만들어야한다.
	Point() {
		
	}
	
	Point(int x, int y) {
		this.x = x;
		this.y = y;
	}
	
	String getLocation() {
		return "(" + this.x + ", " + this.y + ")";
	}

}

//클래스명 : Point3D
//조상클래스 : Point
//멤버변수 : 데이터타입-변수명-용도
//int - z - z좌표
//생성자
// 매개변수가 3개인 생성자 - x, y, z좌표를 전달받아 멤버변수에 저장
//메서드 : 메서드명-반환타입-기능-전달인자
//getLocation - String - xyz 좌표값을 문자열로 반환
class Point3D extends Point{
	
	int z;
	
	Point3D(int x, int y, int z) {
		super();
		this.x = x;
		this.y = y;
		this.z = z;
	}
	
	String getLocation() {
		return "(" + this.x + ", " + this.y + ", " + this.z + ")";
	}
}

📃상속 예제(6) - Tv

//클래스명 : TvIp
//조상클래스명 : Tv
//멤버변수 : 데이터타입-변수명-용도 
//boolean - ipTv - IP 티비 여부를 확인
//생성자
//기본 생성자 : 채널은 0, 음량은 0, IP 티비는 true
//매개변수가 3개인 생성자 : 채널과 음량, ipTv을 전달받아 멤버변수를 초기화
//메서드 메서드명-반환타입-기능-전달인자
//isIpTV - boolean - 없음
class TvIp extends Tv {
	boolean ipTv;
	
	TvIp() {
		super();
		this.ipTv = true;
	}
	
	TvIp(int channel, int volumn, boolean ipTv) {
		super(channel, volumn);
		this.ipTv = ipTv;
	}
	
	boolean isIpTv() {
		return this.ipTv;
	}
	
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return super.toString() + ", " + isIpTv();
	}
}


//클래스명 : Tv
//멤버변수 : 데이터타입-변수명-용도 
// boolean-power-전원on/off
// int-channel-채널
// int-volumn-음량
//생성자
//기본 생성자 : 채널은 0, 음량은 0
//매개변수가 2개인 생성자 : 채널과 음량을 전달받아 멤버변수를 초기화
//메서드 메서드명-반환타입-기능-전달인자
//setChannel - 없음 - 정수값을 입력받아 채널 멤버변수에 저장 - int
//getChannel - int - 멤버변수에 저장된 채널 값을 반환 - 없음
//setVolumn - 없음 - 정수값을 입력받아 음량 멤버변수에 저장 - int
//getVolumn - int - 멤버변수에 저장된 음량 값을 반환 - 없음
//powerOnOff - 없음 - 호출할 때 마다 전원 멤버변수 값을 반전 - 없음
public class Tv {
	public static void main(String[] args) {
		TvIp t = new TvIp(10, 50, true);
		t.powerOnOff();
		
		System.out.println(t);
	}
	boolean power;
	int channel;
	int volumn;
	
	Tv() {
		this(0,0);
	}
	
	Tv(int channel, int volumn) {
		this.channel = channel;
		this.volumn = volumn;
	}
	
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return ", " + channel + ", " + volumn;
	}
	
	void setChannel(int channel) {
		this.channel = channel;
	}
	
	int getChannel() {
		return this.channel;
	}
	
	void setVolumn(int volumn) {
		this.volumn = volumn;
	}
	
	int getVolumn() {
		return this.volumn;
	}
	
	void powerOnOff() {
		power = !power;
		if(power == false) {System.out.println("전원꺼짐");}
		else {System.out.print("전원켜짐");}
	}
}
728x90
반응형

댓글