Try to search your question here, if you can't find : Ask Any Question Now ?

Confusion about late binding (dynamic polymorphism) in java

HomeCategory: stackoverflowConfusion about late binding (dynamic polymorphism) in java
Avatarpushpa asked 4 weeks ago

I am having a superclass “Class B” and subclass “Class C”. Class B and Class C both having private void print(). Class B has public void printPriv(B b) which calls b.print() and Class D has public void printPriv(D d) which calls d.print(). The problem is when executing the main method :

class B {
    private void priv() {
        System.out.println("B");
    }

    public void printPriv(B b) {
        b.priv();
    }
}


class D extends B {
    private void priv() {
        System.out.println("D");
    }

    public void printPriv(D d) {
        d.priv();
    }
}

public static void main(String [] args){
        B b = new B();
        D d = new D();
        b.printPriv(d); 
}

The output is “B” but I expected “D” because of dynamic polymorphism (Late binding) where printPriv() in Class D overrides the one in Class B.

1 Answers
Best Answer
AvatarJyoti answered 4 weeks ago
Your Answer

15 + 14 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com