오버로딩 및 재정의
오버로딩과 오버라이드의 차이점은 무엇입니까?
과부하
오버로딩은 동일한 범위에 이름은 같지만 서명이 다른 메서드가 여러 개있는 경우입니다.
//Overloading
public class test
{
public void getStuff(int id)
{}
public void getStuff(string name)
{}
}
재정의
재정의는 자식 클래스에서 메서드의 기능을 변경할 수있는 원칙입니다.
//Overriding
public class test
{
public virtual void getStuff(int id)
{
//Get stuff default location
}
}
public class test2 : test
{
public override void getStuff(int id)
{
//base.getStuff(id);
//or - Get stuff new location
}
}
오버로딩 및 재정의에 대한 간단한 정의
오버로딩 (컴파일 시간 다형성) :: 이름이 같고 매개 변수가 다른 함수
public class A
{
public void print(int x, int y)
{
Console.WriteLine("Parent Method");
}
}
public class B : A
{
public void child()
{
Console.WriteLine("Child Method");
}
public void print(float x, float y)
{
Console.WriteLine("Overload child method");
}
}
재정의 (런타임 다형성) :: 기본 클래스와 이름과 매개 변수가 같지만 동작이 다른 확장 클래스의 함수.
public class A
{
public virtual void print()
{
Console.WriteLine("Parent Method");
}
}
public class B : A
{
public void child()
{
Console.WriteLine("Child Method");
}
public override void print()
{
Console.WriteLine("Overriding child method");
}
}
제가 배우는 동안 저에게 많은 의미가있는 예를 공유하고 싶습니다.
이것은 가상 메서드 또는 기본 클래스를 포함하지 않는 예제 일뿐입니다. 주요 아이디어에 대한 힌트를 제공합니다.
자동차 세탁기가 있고 "Wash"라는 기능이 있고 Car를 유형으로 수용한다고 가정 해 보겠습니다.
Car 입력을 받고 Car를 세척합니다.
public void Wash(Car anyCar){
//wash the car
}
Wash () 함수를 오버로드합시다.
과부하 :
public void Wash(Truck anyTruck){
//wash the Truck
}
세차 기능은 이전에는 세차 만했지만 지금은 트럭 세차에도 과부하가 걸렸습니다.
- 제공된 입력 객체가 Car이면 Wash (Car anyCar)를 실행합니다.
- 제공된 입력 개체가 Truck이면 Wash (Truck anyTruck)를 실행합니다.
Wash () 함수를 재정의합시다
재정의 :
public override void Wash(Car anyCar){
//check if the car has already cleaned
if(anyCar.Clean){
//wax the car
}
else{
//wash the car
//dry the car
//wax the car
}
}
세차 기능은 이제 차량이 이미 깨끗하고 다시 세차 할 필요가 없는지 확인하는 조건이 있습니다.
차가 깨끗하면 왁스를 칠하십시오.
깨끗하지 않은 경우 먼저 세차 한 다음 건조시킨 다음 왁스를 칠하십시오
.
따라서 새로운 기능을 추가하거나 완전히 다른 작업을 수행하여 기능을 재정의했습니다.
- Overloading = Multiple method signatures, same method name
- Overriding = Same method signature (declared virtual), implemented in sub classes
An astute interviewer would have followed up with:
What's the difference between overriding and shadowing?
As Michael said:
- Overloading = Multiple method signatures, same method name
- Overriding = Same method signature (declared virtual), implemented in sub classes
and
- Shadowing = If treated as DerivedClass it used derived method, if as BaseClass it uses base method.
Having more than one methods/constructors with same name but different parameters is called overloading. This is a compile time event.
Class Addition
{
int add(int a, int b)
{
return a+b;
}
int add(int a, int b, int c)
{
return a+b+c;
}
public static main (String[] args)
{
Addition addNum = new Addition();
System.out.println(addNum.add(1,2));
System.out.println(addNum.add(1,2,3));
}
}
O/p:
3
6
Overriding is a run time event, meaning based on your code the output changes at run time.
class Car
{
public int topSpeed()
{
return 200;
}
}
class Ferrari extends Car
{
public int topSpeed()
{
return 400;
}
public static void main(String args[])
{
Car car = new Ferrari();
int num= car.topSpeed();
System.out.println("Top speed for this car is: "+num);
}
}
Notice there is a common method in both classes topSpeed(). Since we instantiated a Ferrari, we get a different result.
O/p:
Top speed for this car is: 400
in C# there is no Java like hidden override, without keyword override on overriding method! see these C# implementations:
variant 1 without override: result is 200
class Car {
public int topSpeed() {
return 200;
}
}
class Ferrari : Car {
public int topSpeed(){
return 400;
}
}
static void Main(string[] args){
Car car = new Ferrari();
int num= car.topSpeed();
Console.WriteLine("Top speed for this car is: "+num);
Console.ReadLine();
}
variant 2 with override keyword: result is 400
class Car {
public virtual int topSpeed() {
return 200;
}
}
class Ferrari : Car {
public override int topSpeed(){
return 400;
}
}
static void Main(string[] args){
Car car = new Ferrari();
int num= car.topSpeed();
Console.WriteLine("Top speed for this car is: "+num);
Console.ReadLine();
}
keyword virtual on Car class is opposite for final on Java, means not final, you can override, or implement if Car was abstract
shadowing = maintains two definitions at derived class and in order to project the base class definition it shadowes(hides)derived class definition and vice versa.
Another point to add.
Overloading More than one method with Same name. Same or different return type. Different no of parameters or Different type of parameters. In Same Class or Derived class.
int Add(int num1, int num2) int Add(int num1, int num2, int num3) double Add(int num1, int num2) double Add(double num1, double num2)
Can be possible in same class or derived class. Generally prefers in same class. E.g. Console.WriteLine() has 19 overloaded methods.
Can overload class constructors, methods.
Can consider as Compile Time (static / Early Binding) polymorphism.
=====================================================================================================
Overriding cannot be possible in same class. Can Override class methods, properties, indexers, events.
Has some limitations like The overridden base method must be virtual, abstract, or override. You cannot use the new, static, or virtual modifiers to modify an override method.
Can Consider as Run Time (Dynamic / Late Binding) polymorphism.
Helps in versioning http://msdn.microsoft.com/en-us/library/6fawty39.aspx
=====================================================================================================
Helpful Links
http://msdn.microsoft.com/en-us/library/ms173152.aspx Compile time polymorphism vs. run time polymorphism
Overloading is a part of static polymorphism and is used to implement different method with same name but different signatures. Overriding is used to complete the incomplete method. In my opinion there is no comparison between these two concepts, the only thing is similar is that both come with the same vocabulary that is over.
Method overloading and Method overriding are 2 different concepts completely different. Method overloading is having the same method name but with different signatures. Method overriding is changing the default implementation of base class method in the derived class. Below you can find 2 excellent video tutorials explaining these concepts.
Overloading is the concept in which you have same signatures or methods with same name but different parameters and overriding, we have same name methods with different parameters also have inheritance is known as overriding.
참고URL : https://stackoverflow.com/questions/673721/overloading-and-overriding
'programing' 카테고리의 다른 글
UIAlertView 먼저 사용되지 않는 IOS 9 (0) | 2020.08.17 |
---|---|
Angular 2 TypeScript 배열에서 요소를 찾는 방법 (0) | 2020.08.17 |
코드 변경시 Sails.js 앱을 자동으로 다시로드합니까? (0) | 2020.08.16 |
이메일 제목의 애니메이션 아이콘 (0) | 2020.08.16 |
파이썬 내에서 간단한“chmod + x”를 어떻게 수행합니까? (0) | 2020.08.16 |