Search code examples
javavirtualabstract

Abstract/Virtual Functions in java


I've heard that all Java functions are implicitly virtual, but I'm still not sure if this will run how I want.

Suppose I have a class A, with child B. both A and B have functions called foo(), so B's definition is overriding A's.

Suppose also that A has a function called that takes an instance of A as a parameter:

If I pass in an instance of B to the function, which definition of foo() will it call, A's or B's?


Solution

  • As I mentioned in my comment private functions are not virtual and I want to demonstrate it using following example:

    class A {
        public void foo() {
            System.out.println("A#foo()");
        }
    
        public void bar() {
            System.out.println("A#bar()");
            qux();
        }
    
        private void qux() {
            System.out.println("A#qux()");
        }
    }
    
    class B extends A {
        public void foo() {
            System.out.println("B#foo()");
        }
    
        private void qux() {
            System.out.println("B#qux()");
        }
    }
    

    Now lets run following code:

    A foobar = new B();
    foobar.foo(); // outputs B#foo() because foobar is instance of B
    foobar.bar(); // outputs A#bar() and A#qux() because B does not have method bar 
                  // and qux is not virtual