简体   繁体   中英

Is it possible to override a method in same class in Java?

Take a look at the following code sample :

public class Test{

   public static void main(String[] args){

        System.out.println(new Test());


       System.out.println(new Test(){

        public String toString(){
             return "manual override";
         }

       });



      System.out.println(new Test(){

              public String gm(){
                    return  "manual gm";
               }
        }.gm());
     }  //end of main method

   public String gm(){
     return "gm";
    }
}

There may be some argument that the toString() method is being overridden in anonymous inner class which is an entirely different class.
But the overriding code still resides in the same class. So, will it be justified to conclude that in some situations [as described above] , the overriding of a method in same class is possible?

Firstly, you haven't defined toString in your Test.java class.

Secondly, when you make a anonymous class, its is conceptually like creating a subclass. So overriding in anonymous class is allowed as long as parent method is not final.

Mainly, overriding is NOT possible in same class otherwise.

The answer is No, you cannot override the same method in one class. The anonymous inner class is a different class.

The code above overrides toString() method of Object class. So you cannot say that it overrides in the same class. Now also it is overriding a superclass method and here the super class is Object which is the super class of all classes.

No , You can override a method in subclass only.

public String toString(){
         return "manual override";
     }

In your case you are overriding Object's toString() method not Test class method.

In one class we can not have method with same signature. this is because there is no need to have override method in same class.

hence overriding method in same class is not possible, where as if we want to use same method name we can overload method by changing signature.

关于“现实用例”,我确实在Manning的“ JUnit Recipes” 2005的2.5节中找到了上述程序的实际用法。

public class Counter {
private int count;
// a simple integer instance variable
public Counter( ) { }
// default constructor (count is 0)
public Counter(int initial) { count = initial; }
// an alternate constructor
public int getCount( ) { return count; }
// an accessor method
public void increment( ) { count++; }
// an update method
public void increment(int delta) { count += delta; }
// an update method
public void reset( ) { count = 0; }
// an update method
}

Isn;t this function overriding under same class??

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM