CS 241 – Computer Programming II Lab Kalpa Gunaratna –
Contact Contact by Office hours 376 Joshi Mondays & Wednesday 3:00 pm – 4:00 pm
Inheritance Example : A B B is a sub class of A A is the parent class B is the child class
Use extends keyword. public class A { int x = 5; A() { } A(int x) { this.x = x; } public int getX() { return x; } public class B extends A { int y = 10; B(int y) { this.y = y; }
If you do not have the default constructor, you have to call specifically a constructor by keyword super in the child class. public class A { int x = 5; A(int x) { this.x = x; } public int getX() { return x; } public class B extends A { int y = 10; B(int y) { super(5); this.y = y; }
If you want to get parent class’s method behavior to a child class’s method, the parent method should be called in the first place in your child method using the keyword super and equivalent parameters. public class A { int x = 5; A(int x) { this.x = x; } public int getX() { return x; } public int calAge(int val) { int z = val * x; return z; } public class B extends A{ int y = 10; B(int y) { super(5); this.y = y; } public int calAge(int val) { int k = super.calAge(val); k += 3; return k; }
In lab You need to understand extends & super keywords. Do not use protected or instanceOf keywords. Modify the two classes so that no code is redundant and Trekkie is a sub class of Geek. Change code where necessary but the output should match to the original code output.
Post lab Make classes as explained in the assignment. Use polymorphic objects (geeks) in your test code. Draw an UML class diagram for all of your classes so that it clearly represents inheritance from one to another. Submit the UML diagram with your project to WebCT.