>  기사  >  Java  >  Java의 오버로딩 및 재정의

Java의 오버로딩 및 재정의

WBOY
WBOY원래의
2024-08-30 15:43:55605검색

먼저 이름이 무엇을 의미하는지 먼저 살펴보겠습니다. "과부하"는 누군가의 원래 기능에 약간의 추가 부담을 가하는 것을 의미합니다. 그렇죠? 한편, “오버라이딩(Overriding)”은 모든 사람의 원래 기능에 추가로 새로운 기능을 제공하는 것을 의미합니다.  이번 글에서는 Java의 Overloading과 Overriding에 대해 자세히 살펴보겠습니다. 예, Java에서 이를 프로그래밍 방식으로 구현하는 것은 동일한 접근 방식을 따릅니다. 하나씩 살펴보도록 하겠습니다.

Java의 오버로딩

Java 클래스에 이름은 같지만 인수가 다른 여러 메서드가 있는 경우 이를 메서드 오버로딩이라고 합니다. 이름을 동일하게 유지함으로써 프로그램 코드의 가독성을 높일 뿐입니다. 예를 들어, 특정 숫자에 대해 덧셈 연산을 수행해야 한다고 가정해 보겠습니다. 우리 메소드의 이름이 "addition()"이라고 가정해 보겠습니다.  여기서 덧셈은 2개, 3개 또는 그 이상 사이에서 이루어질 수 있습니다. 따라서 추가 연산에 얼마나 많은 숫자가 포함되는지에 따라 함수의 인수(또는 매개변수)를 변경할 수 있습니다. 하지만, 대신에 서로 다른 인수 개수에 대해 서로 다른 메서드를 작성하면 이름이 달라져 인식하기 어려울 수 있습니다.  따라서 오버로드를 통해 코드의 가독성이 향상됩니다. 이제 문제는 어떻게 과부하를 달성할 것인가 하는 것입니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

예제 코드와 함께 하나씩 살펴보겠습니다.

#1 – 매개변수 개수 수정

여기에서는 일부 숫자에 대해 추가 작업을 수행하겠습니다. 이를 위해 "AdditionOperation"이라는 클래스를 만들어 보겠습니다. 해당 클래스 안에 "addition()"이라는 두 개의 메서드가 있습니다. 이러한 방법 중 하나에서는 두 개의 숫자를 추가합니다. 다른 하나에는 세 개의 숫자를 추가하겠습니다. 해당 메소드의 매개변수 수를 변경하여 이를 달성할 것이지만 동일한 이름을 유지할 것입니다. 이런 식으로 여기서 "addition()" 메서드를 오버로드합니다.

코드:

public class AdditionOperation {
static int addition(int num1,int num2){return num1+num2;} //function declarationand definition for addition of two numbers
static int addition(int num1,int num2,int num3){return num1+num2+num3;} //function declarationand definition for addition of three numbers
public static void main(String args[]) {
system.out.printin(addition(35,36)); //method overloading
system.out.printin(addition(35,36,37)); //method overloading, we are calling same methods but for different number of arguments.
}
}

출력:

Java의 오버로딩 및 재정의

#2 – 데이터 유형 수정

여기서는 정수형과 이중형 등 다양한 유형에 대한 덧셈 연산을 해보겠습니다. 이를 위해 "AdditionOperation"이라는 클래스를 만들어 보겠습니다. 해당 클래스 안에 "addition()"이라는 두 개의 메서드가 있다고 가정해 보겠습니다. 이러한 방법 중 하나에서는 두 개의 정수를 추가합니다. 다른 하나에는 두 개의 double을 추가합니다. 해당 메소드의 매개변수 유형을 변경하여 이를 달성할 것이지만 동일한 이름을 유지할 것입니다. 이런 식으로 여기서 "addition()" 메서드를 오버로드합니다.

코드:

public class additionOperation {
static int addition(int num1,int num2){return num1+num2;} //function declarationand definition for addition of two numbers
static double addition(double num1,num2){return num1+num2;} //function declarationand definition for addition of three numbers
public static void main(String args[]) {
system.out.printin(addition(35,36)); //method overloading
system.out.printin(addition(35.5,36.6)); //method overloading, we are calling same methods but for different type of arguments.
}
}

출력:

Java의 오버로딩 및 재정의

과부하 주의사항

  • Overloading in java is basically a “compile-time polym Method Overloading in C#orphism”. Compile-time polymorphism in java is also called “Static method Dispatch” or “Early binding”. So what do I mean by that jargon?
  • As the name suggests, polymorphism is basically an ability to take many forms (poly: many, morph: form). The linking or binding of the overridden function and the object occurs at compile time. Compile-time polymorphism earns its name because function binding to an object occurs early, specifically during compile time, rather than at runtime. It is also called “Early binding” to emphasize this early binding process.
  • Static dispatch is a type of polymorphism or method dispatch that tells how java will select which functionality of the method will be used in compile time. (I mean, whether it will add two or three numbers in our coding example).  The name is also known as the Static method Dispatch.

Overriding in Java

  • When a java subclass or child class has a method that is of the same name and contains the same parameters or arguments and a similar return type as a method that is present in its superclass or parent class, then we can call the method of the child class as an overridden method of the method of its parent class.
  • For example, suppose we need to perform some display operation according to its class type. If I call the method of a parent class, it will display a message defined in a parent class. But, calling the child class method will override the display message of its parent class and display the message defined within the child class method. Hence depending on which display we need to show, we can call the related class (parent or child). We are not changing the method name, argument, and return type here. We are just changing the functionality of the method in the child class. But, instead of this, if we do not do overriding, i. e. we don’t give the specific implementation of the child method, then while calling the method, it will display the same message as present in a parent class.
  • When writing code, use the @Override annotation before overriding a method. This annotation informs the compiler that the method must override a declaration in a superclass. Although using this is not mandatory, it helps prevent errors. If a method annotated with @Override fails to override a method, the compiler generates an error.

Rules for Java Method Overriding

  1. The method must have the same name as in the parent class
  2. The method must have the same parameter as in the parent class.
  3. There must be an IS-A relationship (inheritance).

Code:

//Parent or Super class
class Parent {
public void display() {
system.out.printin("Hello, I am from parent class");
}
}
//Child or sub class
class Sub extends Parent {
//Below method overrides the Parent display() method
// @override
public void display() {
system.out.printin("Hello, I am from child class");
}
}
//Driver class
public class Overriding {
public static void main?(String args[])
{
Parent superObject = new Parent ();
superObject.display(); // Super class method is called
Parent subObject = new Sub();
subObject.display(); //Child class method is called by a parent type reference: this is functionality of method overriding
Sub subObject2 = new Sub(); //Child class method is called by a child type reference
subObject2.display();
}
}

Output:

Java의 오버로딩 및 재정의

Limitations in method Overriding:

  1. The child class cannot override the private methods of the parent class.
  2. You cannot override final methods.
  3. One cannot override static methods.

Points to be Noted for Overriding

  • Overriding in Java represents “run-time polymorphism,” also known as “dynamic method dispatch” or “late binding.” These terms refer to the ability of the Java runtime system to determine the appropriate method implementation to execute based on the actual type of the object at runtime.
  • As the name suggests, polymorphism is basically an ability to take many forms (poly: many, morph: form). So, a call to an overridden function with the object is done during the run time. Hence called run time polymorphism.
  • Late binding, or “dynamic binding,” occurs after compilation during runtime, as it binds functions to objects.
  • Dynamic dispatch is a type of polymorphism or method dispatch that tells how java will select which method functionality will be used in run time. The name is also known as Dynamic method Dispatch.

Conclusion

This concludes our learning of the topic “Overloading and Overriding in Java”. Write the codes mentioned above in the java compiler and check the output. Learning codes will be incomplete if you do not do hands-on by yourself, enhancing your coding skills.  Happy coding!!

위 내용은 Java의 오버로딩 및 재정의의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.