Example 1
Home - About Us
Inheritance and References Example 1 Example 2 Exnample 3

References to super classes

Example 1

Determine the output of the following code:

public class MyPgm
{
	public static void main (String [] args)
	{
		A a = new A();
		a.go();

		B b = new B();
		b.go();

		B b2 = new B();
		A a2;

		a2 = b2;
		a2.go();
		
		a2.fast();  // illegal -- this line won't compile
	}
}

class A
{
	public void go()
	{
		System.out.println("go in A");
	}
}

class B extends A
{
	public void go()
	{
		System.out.println("go in B");
	}

	public void fast()
	{
		System.out.println("fast in B");
	}
}

Example 2

Determine the output of the following code:

public class MyPgm2
{
	public static void main (String [] args)
	{
		B b = new B();
		b.go();

		b.only();
		b.other();
		b.other(27);
		
		A a = new A();
		a.go();
		a.other();
		a.other(77);  // illegal -- this line won't compile
	}
}

class A
{
	public void go()
	{
		System.out.println("go in A");
	}
	
	public void only()
	{
		System.out.println("only in A");
	}
	
	public void other()
	{
		System.out.println("other in A");
	}
}

class B extends A
{
	public void go()
	{
		System.out.println("go in B");
	}

	public void fast()
	{
		System.out.println("fast in B");
	}
	
	public void other(int aParam)
	{
		System.out.println("other with aParam " + aParam + " in B");
	}
}

References and Instance Variables

The following example utilizes the three classes A, B and C:

Each of these classes contains only instance variables.  Note that the polymorphic behavior that applies to methods does not apply to instance variables.

Two of the lines below won't compile. For each call to the println method, below, determine whether or not the line will compile correctly. If it is a valid line of code, then give its output.

Example 3

public class DemoInheritance
{
	public static void main(String args[])
	{
		System.out.println("Starting App");
		A aref = new A();
		B bref = new B();
		C cref = new C();
		
		System.out.println("Values: " + aref.ia);
		System.out.println("Values: " + bref.ib);
		System.out.println("Values: " + cref.ic);
		System.out.println("Values: " + cref.ib);
		System.out.println("Values: " + cref.ia);
		
		A a2;
		a2 = (A) bref;
		
		System.out.println("Num: " + a2.ia);
		System.out.println("Num: " + a2.ib);
		
		B b2 = new C();
		System.out.println("Val: " + b2.ia);
		System.out.println("Val: " + b2.ib);
		System.out.println("Val: " + b2.ic);

		C c2 = (C) b2;
	}
}

class A
{
	int ia = 1;
}
class B extends A
{
	int ib = 2;
}
class C extends B
{
	int ic = 3;
}

 

Home - About Us
Copyright © 2006 by Kiowok, Ann Arbor, Michigan, USA