staff, student..-> 결국하나의 타입으로 묶어줘야됨(상속)
package oop.polymorphism;
//class Person{
// public void job(){}
//}를 추상클래스로 만들기
//추상클래스는 객체 만들지 못함
abstract class Person{
public abstract void job();
}
class Student extends Person{
public void job() {
System.out.println("학생은 공부하기");
}
}
class Staff extends Person{
public void job() {
System.out.println("직원은 업무보기");
}
}
class Teacher extends Person{
public void job() {
System.out.println("선생님은 가르치기");
}
}
class Security extends Person{
public void job() {
System.out.println("보안을 책임집니다");
}
}
public class PolyTest2 {
public static void main(String[] args) {
Student s = new Student();
Staff s2 = new Staff();
Teacher t = new Teacher();
Security sm = new Security();
run(s);
run(s2);
run(t);
run(sm);
}
public static void run (Person obj) {
System.out.println("*******************");
obj.job();
System.out.println("*******************");
}
//아래를 하나로 유지보수 편하게 묶기
// public static void run (Student obj) {
// System.out.println("*******************");
// obj.job();
// System.out.println("*******************");
// }
//
// public static void run (Staff obj) {
// System.out.println("*******************");
// obj.job();
// System.out.println("*******************");
// }
//
// public static void run (Teacher obj) {
// System.out.println("*******************");
// obj.job();
// System.out.println("*******************");
// }
}

package oop.polymorphism;
public class VideoShop {
public static void main(String[] args) {
Content[] content = new Content[3];
content[0] = new Video("변호인","new");
content[1] = new Video("탐정","comic");
content[2] = new Video("헬로카봇","child");
for (int i = 0; i < content.length; i++) {
content[i].totalPrice();
content[i].show();
}
}
}
package oop.polymorphism;
public abstract class Content {
String title;
int price;
public Content() {}
public Content(String title) {
super();
this.title = title;
}
public abstract void totalPrice();
public void show() {
System.out.println(title+" 비디오의 가격은 "+price+"원 입니다.");
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
package oop.polymorphism;
public class Video extends Content {
String genre;
public Video() {}
public Video(String title,String genre) {
super(title);
this.genre = genre;
}
@Override
public void totalPrice() {
if(genre.equals("new")) {
//주소비교하는 ==이 아닌
//문자비교하는 equals("")
setPrice(2000);//이거 몰랐음
}else if(genre.equals("comic")) {
setPrice(1500);
}else if(genre.equals("child")) {
setPrice(1000);
}else {
setPrice(500);
}
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
}

package oop.polymorphism;
public class TestShape {
public static void main(String[] args) {
Shape [] shape = new Shape[2];
shape[ 0 ] = new Circle("원",10);
shape[ 1 ] = new Rectangular("직사각형",10,20);
for (int i = 0; i < shape.length; i++) {
shape[ i ].calculationArea();
shape[ i ].print();
}
}
}
package oop.polymorphism;
public abstract class Shape {
private String name;//얘는 온리 이 클래스에서만
protected double area;//#은 protected: 같은 패키지에 있는 접근가능, 다른패키지여도 상속관계에서 접근가능
public abstract void calculationArea();
public void print() {
System.out.println(name+"의 면적은 "+area);
}
public Shape() {}
public Shape(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getArea() {
return area;
}
public void setArea(double area) {
this.area = area;
}
}
package oop.polymorphism;
public class Circle extends Shape {
private double radius;
public Circle() {}//기본생성자 무조건 만들기
public Circle(String name,double radius) {
super(name);
this.radius = radius;
}
@Override
public void calculationArea() {
area = radius * radius * Math.PI;
//area = Math.PI * Math.pow(radius, 2);//pow는 제곱근 구하는거. 라디어스 2승
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
}
package oop.polymorphism;
public class Rectangular extends Shape {
private double width;
private double height;
public Rectangular() {}
public Rectangular(String name,double width, double height) {
super(name);
this.width = width;
this.height = height;
}
@Override
public void calculationArea() {
area = width * height;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
}

package oop.polymorphism;
public class CoffeShop {
public static void main(String[] args) {
System.out.println("****java nara CoffeeShop영업개시****");
Beverage[] beverage = new Beverage[5];
beverage[0] = new Coffee("Cappuccino");
beverage[1] = new Coffee("CafeLatte");
beverage[2] = new Tea("ginsengTea");
beverage[3] = new Coffee("CafeLatte");
beverage[4] = new Tea("redginsengTea");
getSalesInfo(beverage);
System.out.println("총 판매 금액==>"+getTotalPrice(beverage));
System.out.println("Coffe의 판매 개수=>"+Coffee.amount+"잔");
System.out.println("Tea의 판매 개수=>"+Tea.amount+"잔");
}
//결과와 같이 가격을 구하고 판매정보를 출력할 수 있도록 getSalesInfo메소드를 작성하세요
public static void getSalesInfo(Beverage[] beverage) {//static에서 참조변수 없이 호출해서 static붙여야한대..
for(int i=0;i<beverage.length;i++) {
System.out.print((i+1)+"번째 ");
beverage[i].print();
}
}
//결과와 같이 총 판매금액을 구할 수 있도록 getTotalPrice메소드를 작성하세요.
public static int getTotalPrice(Beverage[] beverage){
int totalPrice = 0;
for(Beverage product:beverage) {
totalPrice = totalPrice + product.getPrice();
}
return totalPrice;
}
}
package oop.polymorphism;
public abstract class Beverage {
private String name;
protected int price;
public abstract void calcPrice();
public void print() {
System.out.println("판매음료는 "+name+"이며, 가격은 "+price);
}
public Beverage() {}
public Beverage(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
package oop.polymorphism;
public class Coffee extends Beverage {
static int amount;
public Coffee() {}
//물건이 구매되면 생성자가 호출 -> 객체 생성이 곧 주문 한 건이라 생각
public Coffee(String name) {
super(name);
amount++;//그래서 이렇게 표시
calcPrice();//주문한 음료에 대해서 금액이 계산
}
@Override
public void calcPrice() {
if(getName().equals("Americano")) {
price = 1500;//price = 1500;//price가 protected 변수라서 이렇게해도됨
}else if(getName().equals("CafeLatte")) {
price = 2500;
}else if(getName().equals("Cappuccino")) {
price = 3000;
}else {
price = 0;
}
}
}
package oop.polymorphism;
public class Tea extends Beverage {
static int amount;
public Tea() {}
public Tea(String name) {
super(name);
amount++;//판매된 티의 갯수를 누적
calcPrice();//판매된 티에 가격 셋팅
}
@Override
public void calcPrice() {
if(getName().equals("lemonTea")) {
price = 1500;
}else if(getName().equals("ginsengTea")) {
price = 2000;
}else if(getName().equals("redginsengTea")) {
price = 2500;
}else {
price = 0;
}
}
}

인터페이스 특징
package oop.polyinter;
interface SuperInterfaceA{
void show();//public abstract void show()와 동일
}
interface InterA extends SuperInterfaceA{
void test();
}
interface InterB{
void change();
}
interface ChildInterface extends InterA, InterB{
}
class MyClass implements InterA, InterB{
@Override
public void show() {
// TODO Auto-generated method stub
}
@Override
public void test() {
// TODO Auto-generated method stub
}
@Override
public void change() {
// TODO Auto-generated method stub
}
}
interface InterC{
}
class MyChild extends MyClass implements InterC{
}
public class interfaceTest01 {
public static void main(String[] args) {
// MyClass obj = new MyChild();
// InterC obj2 = new MyChild();
//다중상속의 효과
MyChild obj = new MyChild();
test(obj);
run(obj);
}
public static void test(MyClass obj) {
}
public static void run(InterC obj) {
}
}
package oop.polyinter;
import oop.polymorphism.Beverage;
import oop.polymorphism.Coffee;
import oop.polymorphism.Tea;
public class InstanceOfTest {
public static void main(String[] args) {
Beverage obj = new Coffee("아메리카노");
Beverage obj2 = new Tea("케모마일");
if(obj instanceof Beverage) {
System.out.println("Beverage타입");
}else {
System.out.println("Beverage타입이 아니다");
}
if(obj instanceof Coffee) {
System.out.println("Coffee타입");
}else {
System.out.println("Coffee타입이 아니다");
}
if(obj instanceof Tea) {
System.out.println("Tea타입");
}else {
System.out.println("Tea타입이 아니다");
}
}
}

package oop.polyinter;
public class AnimalTest {
public static void main(String[] args) {
Animal dog = new Dog(8);
Animal chicken = new Chicken(3);
Chicken cheatableChicken = new Chicken(5);
//Chicken Object가 Cheatable 하다면 fly 함수를 호출
if(cheatableChicken instanceof Chicken){
cheatableChicken.fly();
}
//메인메소드에 코드를 추가해서 도그와 치킨의 이동거리를 출력해주세요
for(int i =1;i<=3;i++) {
dog.run(1);//i대신 1을 넣는 이유 : 누적이 되기때문에 1로해서 알아서 누적시키면됨. 아니면 마지막 i 결과가 됨
chicken.run(1);
cheatableChicken.run(1);
System.out.println(i+"시간 후");
System.out.println("개의 이동거리=" + dog.getDistance());
System.out.println("닭의 이동거리=" + chicken.getDistance());
System.out.println("날으는 닭의 이동거리=" + cheatableChicken.getDistance());
}
}
}
package oop.polyinter;
public abstract class Animal {
int speed;
double distance;
public Animal() {}
public Animal(int speed) {
super();
this.speed = speed;
}
abstract void run(int hours);
double getDistance() {
return distance;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public void setDistance(double distance) {
this.distance = distance;
}
}
package oop.polyinter;
public interface Cheatable {
void fly();;
}
package oop.polyinter;
public class Dog extends Animal {
public Dog(int speed){
super(speed);
}
@Override
public void run(int hours) {
distance = distance + (speed * hours)/2;
}
}
package oop.polyinter;
public class Chicken extends Animal implements Cheatable {
public Chicken(int speed){
super(speed);
}
@Override
public void fly() {
speed = speed * 2;
}
@Override
public void run(int hours) {
distance = distance + (speed * hours);
//setDistance(getDistance() + (speed * hours));//변수가 프라이빗 아니라서 위처럼 해도됨
}
}
본 포스팅은 멀티캠퍼스의 멀티잇 백엔드 개발(Java)의 교육을 수강하고 작성되었습니다.