본문 바로가기

Language/JAVA

[JAVA] 명품 자바 에센셜 예제 5장

 

예제 5-1 : 클래스 상속
문제:(x, y)의 한 점을 표현하는 Point 클래스와 이를 상속받아 점에 색을 추가한 ColorPoint클래스를 만들고 활용해보자

package chap05;

//예제 5-1:클래스 상속
//(x,y)의 한 점을 표현하는 Point클래스와 이를 상속받아 점에 색을 추가한  ColorPoint
//클래스를 만들고 활용해보자.
class Point{
	private int y;
	private int x;
	public Point() {
		System.out.println("기본 생성자");
	}
	
	public Point(int x,int y) {
		this.x=x;
		this.y=y;
	}
	public void showPoint() {
		System.out.println("("+x+","+y+")");;
	}
}

//Point를 상속받은 ColorPoint 선언
class ColorPoint extends Point{
	private String color;
	public void setColor(String color) {
		this.color=color;
	}
	
	public void showColorPoint() {
		System.out.println(color);
		toString();
	}
}

public class ColorPointEx{
	public static void main(String[] args) {
		Point p=new Point();
		Point p2=new Point(1,2);
		p.showPoint();
		p2.showPoint();
		
	}
}
//출력결과
(1,2)
red(3,4)

 

예제 5-2 : super()를 활용한 ColorPoint 작성
문제: super()를 이용하여 ColorPoint 클래스의 생성자에서 서브 클래스 Point 의 생성자를 호출하는 예를 보인다.

package chap05;
//예제 5-2: super()를 활용한 ColorPoint 작성
//super()를 이용하여 ColorPoint 클래스의 생성자에서 서브 클래스 Point의 생성자를 호출하는 예
class Point{
	private int x,y;
	public Point() {
		this.x=0;
		this.y=0;
		
	}
	public Point(int x,int y) {
		this.x=x;
		this.y=y;
	}
	public void showPoint() {
		System.out.println("("+x+","+y+")");
	}
}

 class ColorPoint extends Point{
	 private String color;
	 public ColorPoint(int x,int y, String color) {
		 super(x,y);
		 this.color=color;
	 }
	 public void showColorPoint() {
		 System.out.println();
		 showPoint(n);
	 }
 }
 

 public class SuperEx{
 	public static void main(String[] args) {
 		ColorPoint cp= new ColorPoint(5,6,"blue");
 		cp.showColorPoint();
 	}
 }
//출력결과
blue(5,6)

 

예제 5-3 : instanceof 연산자 활용
문제: instanceof 연산자를 이용하여 [그림 5-15]의 상속 관계에 따라 레퍼런스가 가리키는 객체의 타입을 알아본
다 . 실행 결과는 무엇인가?

package chap05;
//예제 5-3 instanceof 연산자 활용
//instanceof 연산자: 레퍼런스가 가리키는 객체의 타입 식별
class Person{}
class Student extends Person{}
class Researcher extends Person{}
class Professor extends Researcher{}

public class InstanceOfEx {
	static void print(Person p) {
		if(p instanceof Person) {
			System.out.println("Person");
		}
		if(p instanceof Student) {
			System.out.println("Student");
		}
		if(p instanceof Researcher) {
			System.out.println("Researcher");
		}
		if(p instanceof Professor) {
			System.out.println("Professor");
		}
		System.out.println();
	}
	
	public static void main(String[] args) {
		System.out.print("new Student() ->");	print(new Student());
		System.out.print("new Researcher() ->");	print(new Researcher());
		System.out.print("new Professor() ->");	print(new Professor());
	}

}
//출력결과
new Student() --> Person Student
new Researcher() --> Person Researcher
new Professor() --> Person Researcher Professor

 

예제 5-4 : 메소드 오버라이딩으로 다형성 실현
문제 : Shape의 draw() 메소드를 Line, Circle, Rect 클래스에서 목적에 맞게 오버라이딩하는 다형성의 사례를 보여준다.

package chap05;

//예제 5-4
//Shape의 draw()메소드를 Line, Circle, Rect 클래스에서 목적에 맞게 오버라이딩하는 다형성의 사례
class Shape{	//도형의 슈퍼 클래스
	public void draw() {
		System.out.println("Shape Sample");
	}
}
class Line extends Shape{
	public void draw() {
		System.out.println("Line Sample");
	}
}

class Circle extends Shape{
	public void draw() {
		System.out.println("Circle Sample");
	}
}

class Rect extends Shape{
	public void draw() {
		System.out.println("Rect Sample");
	}
}

public class MethodOverridingex {
	static void paint(Shape p) {
		p.draw();
	}

	public static void main(String[] args) {
		Line line=new Line();
		paint(line); //Line의 draw()실행. "Line"출력
		
		paint(new Shape());	//Shape의 draw() 실행. "Shape" 추력
		paint(new Line());	//오버라이딩된 메소드 Line의 draw() 실행
		paint(new Rect());	//오버라이딩된 메소드 Rect의 draw() 실행
		paint(new Circle()); //오버라이딩된 메소드 Circle draw() 실행 
	}

}
//출력결과
Line
Shape
Line
Rect
Circle

 

예제 5-5 : 추상 클래스의 구현
문제: 추상 클래스 Calculator를 상속받는 GoodCalc클래스를 구현하라.

package chap05;

//예제 5-5

abstract class Calculator{//추상 클래스
	public abstract int add(int a,int b);
	public abstract int subtract(int a,int b);
	public abstract double average(int[] a);
}

public class Goodcalc extends Calculator{
	@Override
	public int add(int a,int b) {
		return a+b;
	}
	
	@Override
	public int subtract(int a,int b) {
		return a-b;
	}
	
	@Override
	public double average(int[] a) {
		double sum=0;
		for(int i=0;i<a.length;i++) {
			sum+=a[i];
		}
		return sum/a.length;
	}
	
	
	
	public static void main(String[] args) {
			Goodcalc g=new Goodcalc();
			System.out.println(g.add(2,3));
			System.out.println(g.subtract(2,3));
			System.out.println(g.average(new int[] {2,3,4}));
	}
}
//출력결과
5
-1
3.0

 

예제 5-6 : 인터페이스 구현
문제: PhoneInterface 인터페이스를 구현하고 flash() 메소드를 추가한 SamsungPhone 클래스를 작성하라.

package chap05;
//PhoneInterface 인터페이스를 구현하고 flash()메소드를 추가한 SamsungPhone클래스를 작성하라.
interface PhoneInterface{
	final int TIMEOUT=10000;
	void sendCall();
	void receiveCall();
	default void printLogo() {
		System.out.println("** Phone **");
	}
}

class SamsungPhone implements PhoneInterface{
	//PhoneInterface의 모든 메소드 구현
	@Override
	public void sendCall() {
		System.out.println("전화를 보냅니다.");
	}
	
	@Override
	public void receiveCall() {
		System.out.println("전화가 왔습니다.");
	}
	
	//메소드 추가작성
	public void flash() {
		System.out.println("전화기에 불이 켜졌습니다.");
	}
}

public class InterfaceEx {

	public static void main(String[] args) {
		SamsungPhone phone=new SamsungPhone();
		phone.printLogo();
		phone.sendCall();
		phone.receiveCall();
		phone.flash();
	}

}
//출력결과
** Phone **
띠리리리링
전화가 왔습니다.
전화기에 불이 켜졌습니다.

 

예제 5-7 : 인터페이스 구현과 동시에 슈퍼 클래스 상속

package chap05;
interface PhoneInterface5_7{ //인터페이스 선언
	final int TIMEOUT=10000; //상수 필드 선언
	void sendCall(); //추상 메소드
	void receiveCall(); //추상 메소드
	default void printLogo() {//default메소드
		System.out.println("**Phone**");
	}
}

class Calc{//클래스 작성
	public int calculate(int x,int y) {
		return x+y;
	}
}

class SmartPhone extends Calc implements PhoneInterface5_7{
	//PhoneInterface의 추상 메소드 구현
	
	@Override
	public void sendCall() {
		System.out.println("전화 왔어요.");
	}
	@Override
	public void receiveCall() {
		System.out.println("일정 관리합니다.");
	}
	
	//추가로 작성한 메소드
	public void schedule() {
		System.out.println("일정 관리합니다.");
	}
}


public class InterfaceEx5_7 {

	public static void main(String[] args) {
		SmartPhone phone=new SmartPhone();
		phone.printLogo();
		phone.sendCall();
		System.out.println("3과 5를 더하면 "+phone.calculate(3, 5));
		phone.schedule();
	}

}
//출력결과
** Phone **
따르릉따르릉
3과 5 를 더하면 8
일정 관리합니다.