Java Programming 3

상속 Emample 1
class Dog {
protected String species = "푸들";
public void dark() {
System.out.println("왈왈!");
}
}
public class MyDog extends Dog{
private String myDogName = "흑설탕";
public static void main(String[] args) {
MyDog she = new MyDog();
she.dark();
System.out.println(she.species + " " + she.myDogName);
}
}
실행 결과
왈왈!
푸들 흑설탕

상속 Example 2
class Calculation {
public void addition(int x, int y) {
System.out.println(x + y);
}
public void Subtraction(int x, int y) {
System.out.println(x - y);
}
}
public class My_Calculation extends Calculation {
public void mutiplication(int x, int y) {
System.out.println(x * y);
}
public static void main(String[] args) {
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.mutiplication(a, b);
}
}
실행 결과
30
10
200

Overring 1
class Animal {
public void move() {
System.out.println("동물은 움직입니다.");
}
}
class Dog extends Animal {
public void move() {
System.out.println("강아지는 걷고 뜁니다.");
}
public void bark() {
System.out.println("강아지는 왈왈 짓습니다.");
}
}
public class TestDog {
public static void main(String[] args) {
Animal a = new Animal();
Animal b = new Dog();
a.move();
b.move();
b.bark();
}
}

실행 결과
동물은 움직입니다.
강아지는 걷고 뜁니다.
Overring2
class Animal {
public void move() {
System.out.println("동물은 움직입니다.");
}
}
class Dog extends Animal {
public void move() {
super.move();
System.out.println("강아지는 걷고 뜁니다.");
}
}
public class TestDog {
public static void main(String[] args) {
Animal b = new Dog();
b.move();
}
}
실행 결과
동물은 움직입니다.
강아지는 걷고 뜁니다.

다형성(Polymorphism)
class Animal {
public void run() {
System.out.println("동물은 움직입니다.");
}
}
class Dog extends Animal {
}
class Cat extends Animal {
}
public class TestDog {
public static void doSomething(Animal c) {
c.run();
}
public static void main(String[] args) {
Animal a = new Dog();
Animal b = new Cat();
doSomething(a);
doSomething(b);
}
}
실행 결과
동물은 움직입니다.
동물은 움직입니다.

'프로그래밍 언어 > JAVA' 카테고리의 다른 글
| 패키지 만들기 (0) | 2025.02.25 |
|---|---|
| import와 클래스 경로 (0) | 2025.02.22 |
| 패키지(Package) (0) | 2025.02.19 |
| 인터페이스 (1) | 2025.02.16 |
| 추상 클래스 (0) | 2025.02.13 |