July 7, 2008

Chapter: Reusing Classes

Create two classes, A and B, with default constructors (empty argument lists) that announce themselves. Inherit a new class called C from A, and create a member of class B inside C. Do not create a constructor for C. Create an object of class C and observe the results.


Notice the different output in the two solutions.

In Java:
package chapter.reusingClasses;

class A {
A() {
System.out.println("A");
}
}

class B {
B() {
System.out.println("B");
}
}

class C extends A {
B b = new B();
}

public class Exercise5 {

public static void main(String[] args) {

C c = new C();

}

} /* Output:
A
B
*///


In Python:
class A:
def __init__(self):
print "A"

class B:
def __init__(self):
print "B"

class C(A):
b = B()

C()

# Output:
# B
# A

0 comments: