|
I have a college assignment which I am having trouble with:
Can you store a reference to a superclass object in a subclass reference variable? In each case either give an example or explain why not.
|
|
|
A subclass is everything that its superclass is - it extends the superclass. We usually extend something to change how it behaves or to add something to it. Otherwise, why bother?
Another way of asking the question is: Can a subclass reference be limited to only its superclass? Can an A be exactly a Super and no more?
No. If you say "A a = reference_to_a_Super" then what happens when the reference "a" is used to access something in A that Super does not have? Even "B b = reference_to_a_Super" does not compile.
public class Test
{
public static void main(String[] args)
{
Super s = new Super();
A a = new A();
B b = new B();
System.out.println("s = " + s + "\n" +
"a = " + a + "\n" +
"b = " + b);
if(a instanceof Super)
System.out.println("a instanceof Super");
if(s instanceof A)
System.out.println("s instanceof A");
// cast subclass to its superclass
Super s1 = (Super)a;
System.out.println("s1 = " + s1);
// s1 cannot access anything in A except what A inherited from Super
// s1 is the part of A that was inherited from class Super
// s1 is no longer an A
//System.out.println(s1.aStr); // won't compile
Super s2 = (Super)b;
System.out.println("s2 = " + s2);
// create a Super from an A
Super s3 = new A();
System.out.println("s3 = " + s3);
// do not compile - incompatible types
//A a1 = new Super();
//B b1 = new Super();
// cast superclass to a subclass
// compile but throw ClassCastExceptions at runtime
//A a2 = (A)s;
//B b2 = (B)s;
}
}
class Super
{
String superStr = "I am Super";
public String toString() { return superStr; }
}
class A extends Super
{
String aStr = "I am A";
public String toString() { return aStr; }
}
class B extends Super
{
// nothing extra so B and Super are the same...
}
|
|
|
|
|
In .NET, a superclass is referenced by the "base" reference. So if you want to execute a method called xyz in the base class, you just say base.xyz();.
Hope this helps.
Romel Evans
|
|
|
|
|
|
|
// |