[Java] Method overriding, super keyword vs this keyword

sbj·2023년 11월 26일
0

Java

목록 보기
6/15
post-thumbnail

Method Overriding (메소드 오버라이딩)

We can create a simple example to understand this concept. In this example, I have two classes i.e., Parent class has dogSpeak() method and Child class extends Parent class.

But Child class is not satisfied with the implementation of the catSpeak() method, so the Child (Dog) class is providing implementation of this method in its own way. Thus, the Child class is overriding the dogSpeak() method.

메소드 오버라이딩을 이해하기 위해 간단한 예제를 작성했다. 하기 두 개의 코드를 보자. Parent class는 dogSpeak() 라는 메소드를 갖고, Child class는 Parent 클래스에 extends 한다.

Child 클래스가 catSpeak() 메소드를 이행하고 싶지 않다면? Child 클래스는 자신만의 방식으로 메소드를 수행할 수 있다. 그래서, Child 클래스는 dogSpeak() 메소드를 Overriding 할 수 있다.

Main

public class Main {
public static void main(String[] args) {
	
	Animal animal = new Animal();
	Dog dog = new Dog();
	dog.dogspeak();
	}
}

Dog extends Animal

public class Dog extends Animal {
	void catSpeak() {
		System.out.println("The !Cat! goes bark");
	}
}

Animal

public class Animal {
	void dogSpeak() {
		System.out.println("The !Dog! goes bark");
	}
}

Output

The !Dog! goes bark

→ In the overriding method resolution always takes care of the JVM based on the runtime object hence overriding is also known as runtime polymorphism or dynamic polymorphism or late binding.
오버라이딩 메소드는 항상 런타임 오브젝트를 기반으로한 JVM을 처리하므로, Overriding은 polymorphism, 동적 polymorphism 또는 late binding 이라고도 한다.

→ The process of overriding method resolution is also called dynamic method dispatch.
오버라이딩 메소드의 프로세스는 동적 메소드 디스패치라고도 한다.


Rules for Method Overriding in Java

  1. In the overriding method names and arguments must be the same i.e., the method signature must be the same.
    오버이딩 메소드의 이름과 인수는 항상 같아야 한다.
  2. In method overriding used return types must be the same till Java 1.4 version but from Java 1.5 version onwards co-variant return types are allowed to use.
    메소드 오버라이딩에서는 Java 1.4버전 까지 리턴 타입이 동일해야했으나, Java 1.5 버전부터는 공변환(co-variant) 리턴 타입을 사용할 수 있게 되었다.

Super keyword

Main

public class Main {
	// super = keyword refers to  the superclass(parent) of an object very similar to the "this" keyword.
	public static void main(String[] args) {
		Hero hero1 = new Hero("Batman", 42, "$$$");
		Person hero2 = new Person("Ironman", 50);
		
		hero1.sayHello();
		
		for(int i=0; i< hero1.name.length(); i++) {			
			hero2.sayHello();
			}
		
		System.out.println("==========");
		
		switch(hero1.name) {
		case "Batman":
			System.out.println("It's hero1");
			break;
		case  "Ironman":
			System.out.println("It's hero2");
			break;				
		default:
			System.out.println("It's test for switch case.");
		}
		System.out.println("==========");
		
		System.out.println(hero1.name + ", " + hero1.age + ", " + hero1.power);
			}
}

I apologize for my code. I’m new at Java so I’m playing with Eclipse.

Person

public class Person {
	String name;
	int age;
	Person(String name, int age) { //Constructor
		this.name = name;
		this.age = age;
	}
}

Hero

public class Hero extends Person {
	String power;	
	Hero(String name, int age, String power){
		super(name, age);		
		this.power = power;	
	}
}

What is the ‘super’ keyword?

‘super’ 키워드는 무엇인가?

The ‘super’ keyword in Java is a reference variable that is used to refer to the immediate parent class’s object. It has three primary use cases:

  1. Accessing parent class’s methods
  2. Accessing parent class’s variables
  3. Invoking parent class’s constructor

자바의 ‘super’ 키워드는 직접적으로 Parent 클래스의 객체를 참조할 수 있다.
1. parent class의 메소드에 접근
2. parent class의 변수에 접근
3. parent class의 생성자 호출


The difference between Super() vs this()

So, what is the difference between super() and this()?
그럼, super()와 this()의 차이는 뭘까?

  • super() is used to access methods of the base class while this() is used to access methods of the current class.
  • this() is a reference to the object typed as the current class, and super() is a reference to the object typed as its parent class.

Conclusion

  • These are used within a class or constructor.
  • super() is used to call the parent class’s constructor.
  • this() is used to call the current class’s constructor or to refer to the current class’s instance variable.

내가 이해한 바

  • super() 키워드는, Parent 클래스의 생성자, 메소드를 호출할 때 사용한다. this() 키워드는, Current 클래스 내에서 Constructor or Instance variables를 호출할 때 사용된다.
public class Person {
	String name;
	int age;
	Person(String name, int age) {
		this.name = name;
		this.age = age;
	}
	void sayHello() {
		System.out.println("Hello from Person");
	}
}

public class Hero extends Person {
	String power;
	public Hero(String name, int age, String power){
		super(name, age);		
		this.power = power;	
	}
	void sayHello() {
		System.out.println("Hello from Hero");
	}
}

I can easily understand my code. Look at the above code.
The this() keyword in the Person class calls the current class's instance variables. On the other hand, the super() keyword in the Hero class refers to the Person class's (Parent) instance variables.
내 코드를 보면서 더 쉽게 이해할 수 있었다. this() 키워드는 Person 클래스 = 현재 클래스의 생성자 안에서, Person 클래스 = 현재 클래스의 인스턴스 변수를 참조하고 있다. 반면, super() 키워드는 Hero(Child) 클래스 안에서 Parent 클래스의 name, age라는 인스턴스 변수를 참조하고 있다.


Reference

https://springjava.com/core-java/what-is-overriding-in-java

https://medium.com/@AlexanderObregon/understanding-the-super-keyword-in-java-a-comprehensive-guide-for-interview-preparation-7c1556ead84a

profile
Strong men believe in cause and effect.

0개의 댓글