[Java/자바] Polymorphism, Dynamic polymorphism, Overloading vs Overriding

sbj·2023년 12월 2일

Java

목록 보기
11/15
post-thumbnail

Polymorphism (다형성)

Polymorphism occurs when there is inheritance, i.e., many classes are related.
다형성은 상속이 있을 때 발생하며 많은 클래스들이 관련되어 있다.

Inheritance is a powerful feature in Java. Java Inheritance lets one class acquire the properties and attributes of another class. Polymorphism in Java allows us to use these inherited properties to perform different tasks.
상속은 자바의 강력한 기능으로 → 한 클래스가 다른 클래스의 속성과 특성을 획득할 수 있게 한다. 이러한 상속으로 다양한 작업들을 수행할 수 있게 해준다!

Poly (= numerous), and Morphs(= forms) ⇒ 수많은 형태. 객체지향 프로그래밍의 중요한 특성 중 하나임.


Types of Polymorphism(다형성의 타입)

  1. Method Overloading (메소드 오버로딩)
  2. Method Overriding (메소드 오버라이딩)

✔︎Method Overloading (오버로딩)
1. 동일한 클래스 내에서, 동일한 메소드의 이름으로 → 다양한 메소드를 생성할 수 있다.

✔︎ Method Overriding (오버라이딩)
1. 상위 클래스 ↔ 하위 클래스 간의 관계 중심 ⇒ 하위 클래스가 상위 클래스의 메소드와 동일한 메소드를 가질 때


Examples

Vehicle (Parent 클래스)

public class Vehicle {
	public void go() {
	}
}

Car (Sub 클래스)

public class Car extends Vehicle {
	@Override 
	public void go() {
		System.out.println("The car begins moving.");
	}
}

Boat

public class Boat extends Vehicle {
	@Override
	public void go() {
		System.out.println("The coat begins moving.");
	}
}

Bicycle

public class Bicycle extends Vehicle {
	@Override
	public void go() {
		System.out.println("The bicycle begins moving.");
	}
}

Main

public class Main {
	public static void main(String[] args) {

		Car car = new Car();
		Bicycle bicycle = new Bicycle();
		Boat boat = new Boat();
		
		Vehicle[] racers = {car,bicycle,boat}; // How to store different object using polymorphism
		car.go();
		bicycle.go();
		boat.go();
	
		System.out.println("=======");
		
		for(Vehicle x : racers) {
			x.go();
		}		
	}
}

Points

1

Vehicle[] racers = {car,bicycle,boat}; // How to store different object using polymorphism
		car.go();
		bicycle.go();
		boat.go();
  1. Storing objects is possible in the Car, Bicycle, and Boat classes because these are subclasses of the parent class, Vehicle.
    Vehicle (Parent) 클래스의 오브젝트를 배열에 저장하는 것이 가능하다 → 왜? Sub클래스이니까.

2.

public class Main {
	public static void main(String[] args) {

for(Vehicle x : racers) {
			x.go();
			}	
	}
}
  1. x. go가 가능하기 위해선?
public class Vehicle {
	public void go() {
	}
}	
------------------------------------
@Override
	public void go() {
		System.out.println("The bicycle begins moving.");
	}
  1. 각 Child class의 Method를 @Override 해줘야한다.

Dynamic polymorphism

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		Animal animal ;
	
		System.out.println("What animal do you want?");
		System.out.println("Cat = 1, Dog =2");
		int choice = sc.nextInt();
		if(choice == 1) {
			animal = new Dog();
			animal.speak();
		
		}else if(choice ==2) {
			animal = new Cat();
			animal.speak();
		}
		else {
			animal = new Animal();
			animal.speak();
			System.out.println("That choice is invalid.");
		}
public class Animal {

	public void speak() {
		System.out.println("ㅋ");
	}
}
public class Cat extends Animal {

	@Override
	public void speak() {
		System.out.println("Cat goes meow");
	}
}
public class Dog extends Animal {

	@Override
	public void speak() {
		System.out.println("Dog goes bark");
	}
}

1203 다형성 재복습

Animal

public class Animal {
	public String name;
	private String color;

	public void eat() {
		System.out.println("munch");
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}

}

Dog

package polymorphism2;

//Subclass of Animal Class
//get all the fields and methods from parent class.
public class Dog extends Animal {
	private int breed;

	//Method Overloading
	public void eat() {
		System.out.println("chomp chomp");
	}

	public void eat(int numberOfTimes) {
		for (int i = 0; i < numberOfTimes; i++)
			System.out.println("chomp chomp");
	}

	public void setBreed(int breed) {
		this.breed = breed;
	}

	public void eatFromDog() {
		System.out.println("Dog Class");
	}

}

Main

public class Polymorphism {
	public static void main(String[] args) {
		Animal animal = new Animal();
		animal.eat(); // munch

		Dog myDog = new Dog();
		myDog.eat(); // munch
		myDog.eatFromDog(); // Dog Class
		myDog.eat(3); // This is overladed method.  --> 3 times "chomp chomp"
		Cat myCat = new Cat();
		myCat.eat(); // munch
		myCat.eat(); // nom nom
	}
}

Overloading vs Overriding

오버로딩 vs 오버라이딩

메소드 오버라이딩, 오버로딩의 차이에 대해 정확히 짚고 넘어가야하겠다.

class Car {
	public int sum(int v1, int v2) {
		return v1 + v2;
	}

	// Overloading(오버로딩)
	public int sum(int v1, int v2, int v3) {
		return v1 + v2 + v3;
	}
}

class Car3 extends Car {
	public int minus(int v1, int v2) {
		return v1 - v2;
	}

	// Overriding : Car(부모클래스의) 메소드를 재정의하다. 기능을 추가해서.
	@Override
	public int sum(int v1, int v2) {
		System.out.println("Car3!");
		return v1 + v2;
	}
}

public class InheritanceApp {

	public static void main(String[] args) {
		Car car1 = new Car();

		Car3 car3 = new Car3();
		System.out.println(car3.sum(1, 2, 3)); // Overloading(오버로딩) 6 입력값이 3개이면서, 정수인 sum 메소드를 찾아준다.
		System.out.println(car3.minus(4, 2));
		System.out.println(car3.sum(1, 3));
	}
}

Overloading (오버로딩)

  • Same method name, but different parameters in the same class
    동일한 클래스 내에서 → 동일한 메소드 명, 그러나 다른 파라메터를 가진다.
  • Definition of “loading”
    • the application of a mechanical load or force to something.
      어떤 것에 기계적인 부하나 힘을 가하는 것.
    • the application of an extra amount of something to balance some other factor.
      다른 요소를 균형시키기 위해 무언가 추가적으로 적용하는 것.

Overriding (오버라이딩)

  • It is performed in two classes with inheritance relationships. Method overriding always needs inheritance.
    두 개의 클래스와 상속 관계에서 수행되고, 오버라이딩을 하기 위해 상속이 필요하다.

왜?

  1. Parent & Child Class 관계에서 수행되므로.
  2. Child 클래스에서 기능을 추가해서 Parent Class의 Method를 @Override 해야하니까.
  3. 그러면? @Override 하기 위해선, Same name and Same signature 를 가져야 한다.
  4. 왜? 내가 @Override 하고싶은 Parent 클래스의 메소드를 기능을 추가해서 재정의 하는거니까.
  • Private and Final methods는 Override 할 수 없다.
class Car {
	public int sum(int v1, int v2) {
		return v1 + v2;
	}
--------------------------------------------------------
class Car3 extends Car
@Override
	public int sum(int v1, int v2) {
		System.out.println("Car3!");
		return v1 + v2;
	}
}

profile
Strong men believe in cause and effect.

0개의 댓글