Programmer's Blog

Programmer's reference

[java] virtual functions

source: http://stackoverflow.com/questions/16617291/abstract-virtual-functions-in-java

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
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: