" It is important to understand that it is the type of reference variable - not the type of object that it refers to - that determines what members can be accessed. "
What do you exactly mean by that statement ? Is this restricted to concept of Inheritance ? How does JVM handles it ?
Reference variable is an alternate name of already existing variable. It cannot be changed to refer another variable and should be initialized at the time of declaration and cannot be NULL. The operator '&' is used to declare reference variable. The following is the syntax of reference variable.
Java is always Pass by Value and not pass by reference, we can prove it with a simple example. Let's say we have a class Balloon like below. And we have a simple program with a generic method to swap two objects, the class looks like below.
In Java there are four types of references differentiated on the way by which they are garbage collected. Strong References: This is the default type/class of Reference Object.
It means that suppose you have:
Object x = "hello";
The type of the variable is Object
, but the type of the object it refers to is String
. it's the variable type which determines what you can do though - so you can't call
// Invalid
String y = x.toUpperCase();
The compiler only knows that you're calling a method on Object
, which doesn't include toUpperCase
. Similarly, overloaded methods are only resolved against the ones you know about:
public class Superclass
{
public void foo(Object x) {}
}
public class Subclass extends Superclass
{
public void foo(String y) {}
}
...
Subclass x = new Subclass();
Superclass y = x;
x.foo("hello"); // Calls Subclass.foo(String)
y.foo("hello"); // Calls Superclass.foo(Object)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With