Is every method in Java redefinable

Is every method in Java redefined? I know that in C # methods defined as virtual can be overridden, how is this implemented in Java?

+4
source share
3 answers

Not every method is redefinable: you cannot redefine methods final, privateand static.

below is a small sample of what this means in practice:

class Base {
    public final void fun1() {
    }

    private void fun2() {
        System.out.println("Base::fun2");
    }

    public void fun2Call() {
        fun2();
    }        
}

class Rextester extends Base
{  
    /*
    @Override
    public void fun1() { // compile error, because Base::fun1 is final
    } 
    */

    // if @Override is uncommented, it will protect you from overriding private methods
    //  otherwise you will not get any compile time error.
    //@Override 
    private void fun2() {
        System.out.println("Rextester::fun2");
    }    

    public static void main(String args[])
    {
        Base b = new Rextester();
        b.fun2Call(); // will output Base::fun2,
                      // if you change private to protected or public 
                      // then you will see Rextester::fun2 in output
    }
}

, static - , private , , . , static public protected .

+13

, . .

final , , , , .

static , .

- , .

, JIT , , , , , , . , .

+4

No, not all. Method (s) marked with a modifier final, private, static, they are generally not admissible.

+1
source

Source: https://habr.com/ru/post/1536956/


All Articles