| Author |
Question about constructors and inheritance
|
jo sim
Ranch Hand
Joined: Apr 24, 2006
Posts: 37
|
|
Hi I have three classes Cal, Cal2 and Inheritance5 Cal is parent, Cal2 extends Cal and Inheritance basically tries to find the total. Problem: When I try to compile and execute my Inheritance5.java program it prints 0 instead of 12 why is that and is there a way for me to execute it without using super statement or adding another constructor in child class that accepts 2 ints? Please help. public class Cal { private int base, height, total; Cal(){} Cal(int b, int h) { base = b; height = h; } public void setHeight(int num) { height = num; } public void setBase(int num) { base = num; } public void getTotal() { System.out.println("Area of the rectangle is " + (base*height)); } } ===================================================================== public class Cal2 extends Cal{ } ====================================================================== public class Inheritance5{ public static void main(String[] args){ Cal2 areaRectangle = new Cal2(4,3); areaRectangle.getTotal(); } }
|
 |
Keith Lynn
Ranch Hand
Joined: Feb 07, 2005
Posts: 2341
|
|
|
Are you sure that compiles?
|
 |
jo sim
Ranch Hand
Joined: Apr 24, 2006
Posts: 37
|
|
|
Yes it compiles just fine. These classes are in 3 different java files
|
 |
Keith Lynn
Ranch Hand
Joined: Feb 07, 2005
Posts: 2341
|
|
|
The Inheritance5 class you posted won't compile because there is no constructor in Cal2 that matches int,int.
|
 |
jo sim
Ranch Hand
Joined: Apr 24, 2006
Posts: 37
|
|
|
for some reason it is compiling. but when executing it displays 0 as a value
|
 |
Keith Lynn
Ranch Hand
Joined: Feb 07, 2005
Posts: 2341
|
|
|
If it compiles, you must have a different Cal2 class than what you posted.
|
 |
Srikanth Ramu
Ranch Hand
Joined: Feb 20, 2007
Posts: 76
|
|
As Keith pointed out you can not have the instance of Cal2 accepting 2 ints as parameter with out the constructor. BTW why you do not want to have the constructor in Cal2?
|
 |
 |
|
|
subject: Question about constructors and inheritance
|
|
|