Confusion - Member Availability in Java

67 Views Asked by At

This is a Java question:

When instantiating an Object that has a Reference type that is different from the Object type, what are the scenarios that determine member availability?

For example:

Shape shp = new Square(2, 4); //Where Square extends Rectangle and implements Shape

Will the Shape or Square methods be associated with this code? Does it matter if all methods are static? Does class hiding have any bearing on the choice? If methods are overridden, does that affect the choice?

Here is a more detailed question about the same thing:

public abstract class Writer {
public static void write() {System.out.println("Writing...");}
}
public class Author extends Writer {
public static void write() {System.out.println("Writing book");}
}
public class Programmer extends Writer {
public static void write() {System.out.println("Writing code");}
public static void main(String[] args) {
Writer w = new Programmer();
w.write();
}
}

Why does the code above produce an output -> Writing...

And the following code produces output -> Writing code

public abstract class Writer {
public void write() {System.out.println("Writing...");}
}
public class Author extends Writer {
public void write() {System.out.println("Writing book");}
}
public class Programmer extends Writer {
public void write() {System.out.println("Writing code");}
public static void main(String[] args) {
Writer w = new Programmer();
w.write();
}
}

When instantiating an Object that has a Reference type that is different from the Object type (like this example), what are the scenarios that determine member availability?

1

There are 1 best solutions below

1
Saurav Sahu On

Will the Shape or Square methods be associated with this code? Yes

Methods known to Shape will only be allowed to be called using shp reference variable.

Does it matter if all methods are static?

Polymorphic calls can't be made using shp reference variable if all methods are static.

Does class hiding have any bearing on the choice?

Yes, type of shp reference variable will decide exactly which method gets called. Will be decided at compile-time itself.

If methods are overridden, does that affect the choice?

Static methods are not polymorphic, so there won't exist any overriding scenario.