Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

how does super. work?  RSS feed

 
Sadaf Asrar
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is my code and it's not working so far. I have no idea whats wrong with it. Can anyone figure it out, thanks.

 
Sadaf Asrar
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The class BankAccount works without a problem, however, I can't get the vriable 's' in the subclass Interest to work. I'm getting zeros as my output for the Interest class. Pretty frustrating.
 
Bob Ruth
Ranch Hand
Posts: 320
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For starters when you declare a BankBalance and instantiate it:

BankAccount Balance;
Balance = new BankAccount();

you have indeed created a BankBalance object and then set it's balance at 1000.00.

Later, though, when you declare and instantiate an Interest object:

Interest interest;
interest = new Interest();

you have now created a whole new (and most importantly) separate object of type Interest. Yes, it inherits the state/behavior from a BankBalance object..... just NOT the one that you were working with before! What this is boiling down to is that you created two physically unrelated objects, a BankBalance and an Interest. You set the balance on the BankBalance object, but that has nothing to do with the balance that your Interest object inherited.

The key idea here is that balance is an instance variable. Each instance of a BankBalance has one, and each instance of an Interest object has one. Problem is, they are separate and unique.

What you have to do is declare one object and use the inherited method to set the balance on THAT object, use the inherited methods for all of your other activity, THEN try using the Interest object methods.

Good luck to you.


P.S. One other think to think about..... if a subclass extends a superclass properly and the superclass variable access is set correctly, you dont have to do anything special to access the variable.
[ July 23, 2007: Message edited by: Bob Ruth ]
 
Raj Kumar Bindal
Ranch Hand
Posts: 418
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi sadaf,
instead of
interest = new Interest();
write,
interest = new Interest(Balance);

and in class Interest write,
public Interest(BankAccount act)
{
s = act.balance;
}

hope this will solve your problem.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!