Java Inheritance: Overwritten or hidden methods

Static methods can't be overridden at all. They're not called polymorphically, since they don't act on an instance of the class, but on the class itself.

If you call Maybe.printOut(), it will call the static printOut() method defined in Maybe. The fact that there is also a method printOut() defined in Yes is irrelevant: those two methods have nothing in common, except their name.

Note that you could confirm or infirm your doubts by simply writing a program and executing it.

The problem with hiding methods only occurs when you start calling static methods on an instance of an object. This is very bad practice, and should never be done. If you don't respect this rule, and have the following:

Maybe m = new Maybe();
Maybe y = new Yes();

m.printOut(); // DON'T DO THAT: it should be Maybe.printOut();
y.printOut(); // DON'T DO THAT: it should be Maybe.printOut() or Yes.printOut();

the result will be maybe maybe, because in the case of static methods, what counts is not the concrete type of the objects (Maybe and Yes), but their declared type (Maybe and Maybe).

Answer:1
public class Parent {

    public String test(){
        return "p";
    }

    public static String testStatic(){
        return "sp";
    }
}


public class Child extends Parent {

    public String test(){
        return "c";
    }

    public static String testStatic(){
        return "sc";
    }
}

public class Demo{

    public static void main(String[] args) {

        Parent p =new Parent();
        Child c = new Child();
        Parent pc = new Child();

        System.out.println(p.test());
        System.out.println(c.test());
        System.out.println(pc.test());

            //Although this is not the correct way of calling static methods
        System.out.println(p.testStatic());
        System.out.println(c.testStatic());
        System.out.println(pc.testStatic());
    }
}

OUTPUT will be: - (static method vs instance method)

p c c sp sc sp

Answer:2

I have this program: public class A { public A(){ System.out.println("I am in A"); } public static void main(String args[]){ B a = new B("Test"); } } class B extends A { ...

Reading here, it seems modelling a custom exception class using a generalisation is common place. What it doesn't mention is how I can model an association with a class that could potentially throw ...

I'm really confused with the concept of static vs instance methods. I have created a BMR calculator. I've seperated the GUI from the calculations using different classes. public class Calculations { ...

I need to call some functions generated by some libs. I will need to call fucntion1, function2, ..., function10 one by one. Instead of writing them all out on the code, is there any clever way to code ...