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?