• Post Reply Bookmark Topic Watch Topic
  • New Topic

Question about constructors and inheritance  RSS feed

 
jo sim
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you sure that compiles?
 
jo sim
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes it compiles just fine. These classes are in 3 different java files
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Inheritance5 class you posted won't compile because there is no constructor in Cal2 that matches int,int.
 
jo sim
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
for some reason it is compiling. but when executing it displays 0 as a value
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If it compiles, you must have a different Cal2 class than what you posted.
 
Srikanth Ramu
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!