Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Problem with OOP - Inheritance

  1. #1
    Junior Member
    Join Date
    Dec 2009
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Problem with OOP - Inheritance

    Basically I've made 4 classes, 1 main class, which 3 classes are then extended by. This is the main class file:

    public class Account
    {   
         private float balance;
     
        float getBalance()
        {
            return balance;
        }   
     
    }

    A class file that extends on this is:

    public class Second extends Account
    {
     
         private float balance;
     
        public Loan(float loanBalance)
        {
            balance = loanBalance;
        }
     
    }

    My main class file is:

    public class Main {
     
        public static void main(String[] args)
        {
           Second JoeLoan = new Second(2000);
           float f = JoeLoan.getBalance();
          System.out.println(f);
        }
    }

    This should ideally output 2000.0, however it outputs 0.0... any idea what could be wrong?
    Last edited by connex; December 14th, 2009 at 09:49 PM.


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Problem with OOP - Inheritance

    Look closely at your Second class. It overrides the parent class variable, and so the parent class function will return the balance variable available to it (which is never set, and so will be zero).

    public class Second extends Account
    {
     
         private float balance;//you are overriding the variable from the parent class. Best to omit this line
     
        public Loan(float loanBalance)//Should this be Second and not Loan?
        {
            balance = loanBalance;
        }
     
    }