IT TIP

Java에서 정적 메서드를 재정의하고 오버로드 할 수 있습니까?

itqueen 2020. 12. 14. 21:26
반응형

Java에서 정적 메서드를 재정의하고 오버로드 할 수 있습니까?


알고 싶습니다 :

  1. Java에서 정적 메서드를 재정의 할 수없는 이유는 무엇입니까?
  2. Java에서 정적 메서드를 오버로드 할 수 있습니까?

정적 메서드는 정확한 의미에서 재정의 할 수 없지만 부모 정적 메서드를 숨길 수 있습니다.

실제로 컴파일러는 재정의 된 인스턴스 메서드와 마찬가지로 런타임이 아닌 컴파일 시간에 실행할 메서드를 결정합니다.

깔끔한 예를 보려면 여기를보십시오 .

그리고 이것은 인스턴스 메소드 재정의클래스 (정적) 메소드 숨기기 의 차이점을 설명하는 Java 문서 입니다.

재정의 : Java에서 재정의한다는 것은 단순히 특정 메서드가 개체의 컴파일 타임 유형이 아니라 객체의 런타임 유형에 따라 호출된다는 것을 의미합니다 (이는 재정의 된 정적 메서드의 경우).

숨기기 : 정적 인 부모 클래스 메서드는 액세스 할 수 있지만 자식 클래스의 일부가 아니므로 재정의 할 필요가 없습니다. 상위 클래스에있는 것과 동일한 다른 정적 메서드를 하위 클래스에 추가하더라도이 하위 클래스 정적 메서드는 고유하고 상위 클래스의 정적 메서드와 다릅니다.


재정의 할 것이 없기 때문에 정적 메서드는 재정의 할 수 없습니다. 두 가지 다른 메서드이기 때문입니다. 예를 들면

static class Class1 {
    public static int Method1(){
          return 0;
    }
}
static class Class2 extends Class1 {
    public static int Method1(){
          return 1;
    }

}
public static class Main {
    public static void main(String[] args){
          //Must explicitly chose Method1 from Class1 or Class2
          Class1.Method1();
          Class2.Method1();
    }
}

그리고 예, 정적 메서드는 다른 메서드와 마찬가지로 오버로드 될 수 있습니다.


정적 메서드는 런타임에 개체 인스턴스에 전달되지 않으므로 재정의 할 수 없습니다. 컴파일러는 호출되는 메서드를 결정합니다.

이것이 당신이 작성할 때 컴파일러 경고를받는 이유입니다.

 MyClass myObject = new MyClass();
 myObject.myStaticMethod();
 // should be written as
 MyClass.myStaticMethod()
 // because it is not dispatched on myObject
 myObject = new MySubClass();
 myObject.myStaticMethod(); 
 // still calls the static method in MyClass, NOT in MySubClass

정적 메서드는 오버로드 될 수 있습니다 (즉, 매개 변수 유형이 다른 한 여러 메서드에 대해 동일한 메서드 이름을 가질 수 있음).

 Integer.parseInt("10");
 Integer.parseInt("AA", 16);

정적 인 부모 클래스 메서드는 액세스 할 수 있지만 자식 클래스의 일부가 아니므로 재정의 할 필요가 없습니다. 상위 클래스에있는 것과 동일한 다른 정적 메서드를 하위 클래스에 추가하더라도이 하위 클래스 정적 메서드는 고유하고 상위 클래스의 정적 메서드와 다릅니다.


정적 메서드는 개체 상태의 일부가 아니므로 재정의 할 수 없습니다. 오히려 클래스에 속합니다 (즉, 클래스 메서드입니다). 정적 (및 최종) 메서드를 오버로드하는 것은 괜찮습니다.


하위 클래스 이름 MysubClass를 사용하여 메서드를 호출하는 경우 하위 클래스 메서드는 정적 메서드를 재정의 할 수 있는지 여부를 표시합니다.

class MyClass {
    static void myStaticMethod() {
        System.out.println("Im in sta1");
    }
}

class MySubClass extends MyClass {

    static void  myStaticMethod() {
        System.out.println("Im in sta123");
    }
}

public class My {
    public static void main(String arg[]) {

        MyClass myObject = new MyClass();
        myObject.myStaticMethod();
        // should be written as
        MyClass.myStaticMethod();
        // calling from subclass name
        MySubClass.myStaticMethod();
        myObject = new MySubClass();
        myObject.myStaticMethod(); 
        // still calls the static method in MyClass, NOT in MySubClass
    }
}

정적 메서드는 클래스의 모든 개체가 단일 복사본을 공유하는 메서드입니다. 정적 메소드는 객체가 아닌 클래스에 속합니다. 정적 메소드는 객체에 의존하지 않기 때문에 Java 컴파일러는 객체 생성까지 기다릴 필요가 없습니다. 그래서 우리는 ClassName.method ()와 같은 구문을 사용하는 정적 메소드를 호출합니다.

메서드 오버로딩의 경우 메서드는 동일한 클래스에 있어야합니다. 정적으로 선언 된 경우에도 다음과 같이 오버로드 할 수 있습니다.

   Class Sample
    {
         static int calculate(int a,int b,int c)
           {
                int res = a+b+c;
                return res;
           }
           static int calculate(int a,int b)
           {
                int res = a*b;
                return res;
           }
}
class Test
{
   public static void main(String []args)
   {
     int res = Sample.calculate(10,20,30);
   }
}

그러나 메서드 오버라이드의 경우 수퍼 클래스의 메서드와 하위 클래스의 메서드가 다른 메서드로 작동합니다. 수퍼 클래스는 자체 복사본을 가지며 하위 클래스는 자체 복사본을 가지므로 메서드 재정의 아래에 있지 않습니다.


아니요, 정적 메서드는 개체가 아닌 클래스의 일부이므로 재정의 할 수 없습니다. 그러나 정적 메서드를 오버로드 할 수 있습니다.


static방법은 class레벨 방법입니다.

static방법 에는 개념 숨기기가 사용됩니다 .

참조 : http://www.coderanch.com/how-to/java/OverridingVsHiding


오버로딩은 정적 바인딩이라고도하므로 static이라는 단어가 사용되는 즉시 정적 메서드가 런타임 다형성을 표시 할 수 없음을 의미 합니다 .

정적 메서드를 재정의 할 수는 없지만 수퍼 클래스와 그 하위 클래스에 동일한 정적 메서드의 다른 구현이있는 것은 유효합니다. 파생 클래스가 기본 클래스의 구현을 숨길뿐입니다.

정적 메서드의 경우 메서드 호출은 참조되는 개체가 아니라 참조 유형에 따라 달라집니다. 즉, 정적 메서드는 인스턴스가 아닌 클래스에만 속하므로 컴파일 타임 자체에 메서드 호출이 결정됩니다.

메서드 오버로딩의 경우 정적 메서드는 다른 개수 또는 매개 변수 유형이있는 경우 오버로드 될 수 있습니다 . 두 메서드의 이름과 매개 변수 목록이 같으면 'static'키워드를 사용해서 만 다르게 정의 할 수 없습니다.


class SuperType {

    public static void  classMethod(){
        System.out.println("Super type class method");
    }
    public void instancemethod(){
        System.out.println("Super Type instance method");
    }
}


public class SubType extends SuperType{


    public static void classMethod(){
        System.out.println("Sub type class method");
    }
    public void instancemethod(){
        System.out.println("Sub Type instance method");
    }
    public static void main(String args[]){
        SubType s=new SubType();
        SuperType su=s;
        SuperType.classMethod();// Prints.....Super type class method
        su.classMethod();   //Prints.....Super type class method
        SubType.classMethod(); //Prints.....Sub type class method 
    }
}

정적 메서드 재정의에 대한이 예

Note: if we call a static method with object reference, then reference type(class) static method will be called, not object class static method.

Static method belongs to class only.


From Why doesn't Java allow overriding of static methods?

Overriding depends on having an instance of a class. The point of polymorphism is that you can subclass a class and the objects implementing those subclasses will have different behaviors for the same methods defined in the superclass (and overridden in the subclasses). A static method is not associated with any instance of a class so the concept is not applicable.

There were two considerations driving Java's design that impacted this. One was a concern with performance: there had been a lot of criticism of Smalltalk about it being too slow (garbage collection and polymorphic calls being part of that) and Java's creators were determined to avoid that. Another was the decision that the target audience for Java was C++ developers. Making static methods work the way they do have the benefit of familiarity for C++ programmers and were also very fast because there's no need to wait until runtime to figure out which method to call.


The very purpose of using the static method is to access the method of a class without creating an instance for it.It will make no sense if we override that method since they will be accessed by classname.method()


No, you cannot override a static method. The static resolves against the class, not the instance.

public class Parent { 
    public static String getCName() { 
        return "I am the parent"; 
    } 
} 

public class Child extends Parent { 
    public static String getCName() { 
        return "I am the child"; 
    } 
} 

Each class has a static method getCName(). When you call on the Class name it behaves as you would expect and each returns the expected value.

@Test 
public void testGetCNameOnClass() { 
    assertThat(Parent.getCName(), is("I am the parent")); 
    assertThat(Child.getCName(), is("I am the child")); 
} 

No surprises in this unit test. But this is not overriding.This declaring something that has a name collision.

If we try to reach the static from an instance of the class (not a good practice), then it really shows:

private Parent cp = new Child(); 
`enter code here`
assertThat(cp.getCName(), is("I am the parent")); 

Even though cp is a Child, the static is resolved through the declared type, Parent, instead of the actual type of the object. For non-statics, this is resolved correctly because a non-static method can override a method of its parent.


You can overload a static method but you can't override a static method. Actually you can rewrite a static method in subclasses but this is not called a override because override should be related to polymorphism and dynamic binding. The static method belongs to the class so has nothing to do with those concepts. The rewrite of static method is more like a shadowing.


I design a code of static method overriding.I think It is override easily.Please clear me how its unable to override static members.Here is my code-

class Class1 {
    public static int Method1(){
          System.out.println("true");
          return 0;
    }
}
class Class2 extends Class1 {
    public static int Method1(){
   System.out.println("false");
          return 1;
    }

}
public class Mai {
    public static void main(String[] args){
           Class2 c=new Class2();
          //Must explicitly chose Method1 from Class1 or Class2
          //Class1.Method1();
          c.Method1();
    }
}

It’s actually pretty simple to understand – Everything that is marked static belongs to the class only, for example static method cannot be inherited in the sub class because they belong to the class in which they have been declared. Refer static keyword.

The best answer i found of this question is:

http://www.geeksforgeeks.org/can-we-overload-or-override-static-methods-in-java/


As any static method is part of class not instance so it is not possible to override static method

참고URL : https://stackoverflow.com/questions/2475259/can-i-override-and-overload-static-methods-in-java

반응형