user3478590
user3478590

Reputation: 83

java inheritance misunderstanding

The first question is inside the code. The second question is why static methods can't be overridden to be non-static methods? The third is why can't static and abstract go together?

class A {  
    public void display() {  
        System.out.println("Display of Class A called");  
    }  
}  

class B extends A {  
    public void display() {  
        System.out.println("Display of Class B called");  
    }  
}  

class C extends B {  
    public void display() {  
        System.out.println("Display of Class C called");  
        super.display(); // calls B's Display  
        // Is there a way to call A's display() from here? 
    }  
}

Upvotes: 0

Views: 68

Answers (2)

kevin
kevin

Reputation: 2213

First question: no you can't call the bass class's bass class directly, since in class C's view, it has no idea that class B has a bass class and it's class A. All that's know by C is that it has a base class, and it's B.

Second question: static methods are simply a neat way to organize global methods. There's no inheritance. You just put that method to a class so when you write code to call it, you know where to locate it.

Third question: abstract means "this is what the class to do, here are some basic functionality, but I cannot finish this; inherit me and finish whatever is left to get it working". As mentioned earlier, static method is just a way to put methods that "stand by themselves", requires no initialization and no context. The two does not go together.

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279990

[B] // Is there a way to call A's Display from here???[/B]

No, you can't go two steps up in the class hierarchy. You could implement and call a method in B which would invoke the A implementation.

why static methods can't be overridden to be non-static methods

static methods are associated with a class. Polymorphism (and thus overriding) is a concept that applies to objects and therefore does not apply to them.

why can't static and abstract go together

For the same reason given above. An abstract method is a method that should be implemented in a sub class because the sub class inherited it. Since a sub class does not inherit a static method, a static method cannot be abstract.

Upvotes: 3

Related Questions