package a.b;

public class Shape {
	
	public double res=0; 
	
	public double area(){
		return res;
	}

}




package a.b;

public class Circle extends Shape{
	//Shape클래스에서 상속받은 필드와 메소드
	/*public double res=0; 

	public double area(){
		return res;
	}*/ 
	
	public int r=5;
	public double area(){
		res=r*r*Math.PI;
		return res;
	}
}




package a.b;

public class Rectangle extends Shape{
	//Shape클래스에서 상속받은 필드와 메소드
	/*public double res=0; 

	public double area(){
		return res;
	}*/ 
	
	//줄마춤 ctrl+shift+f
	public int w=10;
	public int h=10;
	
	public double area(){
		res=w*h;
		return res;
	}
}




package a.b;

public class Triangle extends Shape{
	//Shape클래스에서 상속받은 필드와 메소드
	/*public double res=0; 

	public double area(){
		return res;
	}*/ 
	
	public int w=5;
	public int h=10;
	public double area(){
		res=w*h*0.5;
		return res;
	}
	
}




package c.d;

import a.b.Circle;
import a.b.Rectangle;
import a.b.Shape;
import a.b.Triangle;


public class Test {

	public static void main(String[] args) {
		Shape ref= null;
		ref =new Circle();// UpCasting
		System.out.println("도형의 면적은 " +ref.area());
		ref =new Rectangle();// UpCasting
		System.out.println("도형의 면적은 " +ref.area());
		ref =new Triangle();// UpCasting
		System.out.println("도형의 면적은 " +ref.area());

	}
}
위에 출력문을 for문으로 변경
package c.d;

import a.b.Circle;
import a.b.Rectangle;
import a.b.Shape;
import a.b.Triangle;


public class Test {

	public static void main(String[] args) {
		Shape[] shapes = new Shape[3];
		shapes[0] =new Circle();// UpCasting
		shapes[1] =new Rectangle();// UpCasting
		shapes[2] =new Triangle();// UpCasting
		
		for(int i=0;i<shapes.length;i++){
			System.out.println("도형의 면적은 :" +shapes[i].area());
		}
	}
}




package c.d;

import a.b.Circle;
import a.b.Rectangle;
import a.b.Shape;
import a.b.Triangle;


public class Test {

	public static void main(String[] args) {
		Shape[] shapes = new Shape[3];
		shapes[0] =new Circle();// UpCasting
		shapes[1] =new Rectangle();// UpCasting
		shapes[2] =new Triangle();// UpCasting
		
		for(int i=0;i<shapes.length;i++){
			System.out.println("도형의 면적은 :" +shapes[i].area());
		}
		if(shapes[0] instanceof Circle){
			System.out.println("Circle의 객체가 맞습니다.");
		}else{
			System.out.println("Circle의 객체가 아닙니다.");
		}
		if(shapes[2] instanceof Circle){
			System.out.println("Circle의 객체가 맞습니다.");
		}else if(shapes[2] instanceof Rectangle){
			System.out.println("Rectangle의 객체가 맞습니다.");
		}else if(shapes[2] instanceof Triangle){
			System.out.println("Triangle의 객체가 맞습니다.");
		}
		else{
			System.out.println("모르겠다.");
		}
	}
}

도형의 면적은 :78.53981633974483

도형의 면적은 :100.0

도형의 면적은 :25.0

Circle의 객체가 맞습니다.

Triangle의 객체가 맞습니다.


'Java > 2012.04 강좌' 카테고리의 다른 글

9일차 calculator  (0) 2012.04.16
9일차 상속2  (0) 2012.04.16
9일차 복습 상속  (0) 2012.04.16
9일차 복습  (0) 2012.04.16
8일차 Inheritance(상속)2  (0) 2012.04.13

+ Recent posts