Having trouble understand the small details of Inheritance in Java

Viewed 67

I was learning about Inheritance of classes in Java, and I have trouble understanding how it works.

For example, consider this:

class SalesPerson {
    public void sale() {
        System.out.print("greet ");
        pitch();
    }
    
    public void pitch() {
        System.out.print("pitch ");
    }
}

class CommissionedSalesPerson extends SalesPerson {
    public void sale() {
        super.sale();
        System.out.print("record ");
    }
    
    public void pitch() {
        super.pitch();
        System.out.print("close ");
    }
}

When I do

    SalesPerson Vincent = new CommissionedSalesPerson();
    Vincent.sale();

I expect the output to be greet pitch record, however, we get greet pitch close record. So I thought that maybe super classes method, unless mentioned with this use the sub-class method. But, adding to the confusion, when I did this:

class SalesPerson {
    private String PitchString = "Hello! ";
    
    public void sale() {
        System.out.print("greet ");
        System.out.print(PitchString);
    }
    
    public void pitch() {
        System.out.print("Pitch ");
    }
}

class CommissionedSalesPerson extends SalesPerson {
    private String PitchString = "Commissioned Hello! ";
    
    public void sale() {
        super.sale();
        System.out.print("record ");
    }
    
    public void pitch() {
        super.pitch();
        System.out.print("close ");
    }
}

I expect (similar to above)

greet Commissioned Hello! record

but got

greet Hello! record

I'd appreciate if someone could explain how methods are called in Class Inheritance in Java and why are they called like that (so I don't have to memorize and forget later).

0 Answers
Related