A test example illustrating inheritance. Try to figure out the results without running the program.


public class Inh {
    public static void main(String [] args) {
	A a = new A();
	System.out.println(a);
	a.m();
	System.out.println(a);

	B b = new B();
	System.out.println(b);
	b.m();
	System.out.println(b);
	System.out.println((A) b);

	C c = new C();
	System.out.println(c);
	c.m();
	System.out.println(c);
    }
}

class A {
    private int x;

    // constructor 
    public A() {
	x = 1;
    }

    public String toString () {
	return "A: x = " + x;
    }

    public void m () {
	x++;
    }
}


class B extends A {
    protected int y;

    public String toString () {
	return "B: y = " + y + " " + super.toString();
    }   

    public void m() {
	y++;
    }
}


class C extends B {
    private int z;

    public C() {
	z = 3;
    }
    
    public String toString () {
	return "C: z = " + z + " y = " + y + " " + super.toString();
    } 
}


This is an example from CSci 1211 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.