Results 1 to 4 of 4
Thread: Problem when Overloading Classes
- 04-12-2012, 04:41 AM #1
Senior Member
- Join Date
- Jan 2012
- Posts
- 146
- Rep Power
- 0
Problem when Overloading Classes
Okay, so I tried to overload my class, and it is fairly simple. I made the methods, called the variables etc.
But when I run it, it gives me 0 for the product (or area) of the length * width.
In the first AreaRect I initialize the variables and I thought it should work. Second I just call them, but initialize them later in my object creation.Java Code:public class AreaRect { int length; int width; AreaRect(){ int length = 7; int width = 5; } AreaRect(int l, int w){ int length = l; int width = w; } int getArea(){ return length * width; } public static void main(String [] args){ AreaRect RectObj1 , RectObj2; RectObj1 = new AreaRect(); RectObj2 = new AreaRect(10, 20); System.out.println("Area of rectangle 1 is:" + RectObj1.getArea()); System.out.println("Area of rectangle 2 is:" + RectObj2.getArea()); } }
Can someone help me get the correct answers (35 and 200)?
-
Re: Problem when Overloading Classes
You're re-declaring variables in your constructors which will "shadow" the class variables. Don't do this, but instead use the class variables in the constructors.
- 04-12-2012, 04:54 AM #3
Senior Member
- Join Date
- Jan 2012
- Posts
- 146
- Rep Power
- 0
Re: Problem when Overloading Classes
Okay, do I really need to even declare my variables in AreaRect(1)?
- 04-12-2012, 09:07 AM #4
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,406
- Blog Entries
- 7
- Rep Power
- 17
Similar Threads
-
Function Overloading
By ankiit in forum New To JavaReplies: 7Last Post: 08-20-2012, 08:43 PM -
Overloading or Overriding...
By chathura87 in forum New To JavaReplies: 5Last Post: 02-22-2011, 01:46 AM -
overloading
By Bhuvan in forum Advanced JavaReplies: 6Last Post: 01-02-2011, 09:15 AM -
Overloading qn
By diskhub in forum New To JavaReplies: 18Last Post: 06-07-2010, 05:19 PM -
Overloading?
By padutch2 in forum New To JavaReplies: 2Last Post: 12-31-2007, 03:26 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks