본문 바로가기

자바

오버라이딩, 추상 메소드, 상속, 인터페이스

33)

class Shape {

public void draw() { System.out.println("Shape"); }

}

class Line extends Shape {

public void draw() { System.out.println("Line");} // 오버라이딩

}

 

public class temp {

public static void paint(Shape p) { // Shape 상속받은 객체들이 매개 변수로 넘어올 수 있음

p.draw(); // 동적바인딩, p 가리키는 객체에 오버라이딩된 draw() 호출

}

public static void main(String[] args) {

Line line = new Line();

paint(line); // Line draw() 실행

 

paint(new Shape()); // Shape draw() 실행

paint(new Line()); // 오버라이딩된 메소드 Line draw()실행

}

}

 

34)

package school;

 

class SuperObject{

protected String name;

public void paint() {draw();}

public void draw() {System.out.println(name);}

}

 

public class temp2 extends SuperObject{

protected String name;

public void draw() {

name="Sub";

super.name="Super"; // Super

super.draw();

System.out.println(name); // Sub

}

public static void main(String[] args) {

SuperObject b= new temp2();

b.paint();

}

}

 

35)

package temp;

 

abstract class Calc{ // 추상 메소드를 가진 추상 클래스

// 온전한 클래스가 아니기에 인스턴스를 생성 불가능

// Calc c= new Calc(); // 컴파일 오류

/* 컴파일 오류

Calc c;

c=new Calc();

*/

// 추상 메소드가 없는 추상 클래스도 존재

public abstract int add(int a, int b); // 추상 메소드, 메소드의 코드는 없고 원형만 선언되어있는 형태

public abstract int subtract(int a, int b);

public abstract double average(int[] a);

}

 

public class temp4 extends Calc{

@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) {

temp4 c= new temp4();

System.out.println(c.add(2,3));

System.out.println(c.subtract(2,3));

System.out.println(c.average(new int[] {2,3,4}));

}

}

 

36)

abstract class A { // 추상 클래스

abstract public int add(int x, int y); // 추상 메소드

}

abstract class B extends A { //추상 클래스 상속시 자식 클래스도 추상클래스

public void show() { System.out.println("B"); }

}

 

class C extends A { // 추상 클래스 구현, C는 정상 클래스

public int add(int x, int y) { return x+y; } // 추상 메소드 구현(오버라이딩)

public void show() { System.out.println("C"); }

}

C c = new C(); // 추상 클래스를 구현한 서브 클래스는 추상클래스가 아니므로 주의

// 추상 클래스는 상속을 위한 슈퍼 클래스로 활용하기 위해 사용, 서브 클래스에서 추상 메소드 구현하여 다형성을 실현

 

37)

package school;

 

interface PhoneInterface{ // 필드 선언 불가, (public) interface

// 상수: public 허용, public/ static/ final 생략 가능

// 추상 메소드: public abstract 생략 가능

// default 메소드: public 접근 지정만 허용, 생략가능

// private 메소드: 인터페이스 내에 메소드 코드가 작성되어야 하며 인터페이스내에 있는 다른 메소드에 의해서만 호출가능

// static 메소드: public/ private 지정 가능, 생략시 private

final int TIMEOUT=10000; // 상수, (public static final) int

void sendCall(); // (public static final) void

void receiveCall(); // (abstract public) void

default void printLogo() { // default 명시필요

System.out.println("**Phone**");

}

// 인터페이스는 객체 생성 불가하지만 인터페이스 타입의 레퍼런스 변수 선언은 가능

// new PhoneInterface(); // 컴파일 오류

//PhoneInterface A; // A는 인터페이스에 대한 래퍼런스 변수

// extends 상속이 가능하며 다중 상속 허용

}

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 temp5 {

 

public static void main(String[] args) {

SamsungPhone phone=new SamsungPhone();

phone.printLogo(); phone.sendCall();

phone.receiveCall(); phone.flash();

}

}

 

37)

package school;

 

interface InterFood{

void cook();

void taste();

}

 

abstract class Food implements InterFood{

private String foodName;

// public Food(){ this.foodName="";};

public Food(String s) {this.foodName=s;}

 

public String getfoodName() { return this.foodName;} // public 작성 필수

public String setfoodName(String s) { return this.foodName=s;}

}

 

class Noodle extends Food{

@Override

public void cook() { System.out.println("끓는 물에 라면과 스프를 넣고 2분간 끓인다");}

@Override

public void taste() {System.out.println("개운하고 구수한 맛이 난다");}

public Noodle(String s) {super(s);}

}

class FriedRice extends Food{

@Override

public void cook() { System.out.println("밥과 각종 야채를 기름에 볶는다");}

@Override

public void taste() {System.out.println("밥이 고슬고슬하고 잘 볶아진 야채가 잘 어울러진다");}

public FriedRice(String s) {super(s);}

}

 

public class temp6 {

public static void main(String[] args) {

Food[] f= new Food[2];

f[0]=new Noodle("라면"); f[1]=new FriedRice("볶음밥");

for(int i=0; i<2; i++) {

System.out.println("음식명: "+f[i].getfoodName());

System.out.print("요리법: "); f[i].cook(); // 값을 리턴하지 않기때문에 따로 처리

if(f[i] instanceof Noodle) System.out.println("파를 넣는다");

System.out.print("음식맛: "); f[i].taste();

System.out.println("**************");

 

// System.out.println("요리법: "+f[i].cook()); // 컴파일 오류

// System.out.println("음식맛: "+f[i].taste()); // 컴파일 오류

}

}

}

 

'자바' 카테고리의 다른 글

업캐스팅, 다운캐스팅, instance of  (0) 2024.05.02
접근지정자, super()  (0) 2024.05.02
this(), this. , 배열 객체 래퍼런스  (0) 2024.05.02
배열, for-each문, try-catch-finally문  (0) 2024.05.02
자바 기본  (1) 2024.05.02