简体   繁体   中英

inheritance and polymorphism java

I have base class, Customer and sub-classes Acc1 up till 3.

When I am reading a file to initialize my array of customer objects, they all just show up as empty. As I find out what account type the customer has I assign the variable to the respective object(temp1-3, first1-3). Not quite sure why they remain empty.

I am pasting my class definitions for the base and one of the derived classes. The error occurs in the readFile() method when I assign first and temp (Customer class objects_ to first(1/2/3) and temp(1/2/3) (sub classes, Account1, Account2 and Account3).

Not sure if the class definitions are wrong as I simply call the super constructor in all of them. tried debugging it but with no success. Help will be appreciated.

package lab4;

import java.io.*;
import java.util.*;


public class lab4{
    static int count =0; // number of records read or written
    public static void main(String args[])
        throws IOException
    {

        Customer[] records = new Customer[30];
        for (int j=0; j<30; j++){
            records[j] = new Customer();
        }

        menu(records);
    }



    public static int readFile(String filename, Customer[] review)
        throws IOException
    {

        Scanner scan = new Scanner (new File (filename));

        /*Reading the first record separatly*/
        Customer first = new Customer();
        Account1 first1= new Account1();
        Account2 first2= new Account2();
        Account3 first3 = new Account3();

        String[] a = scan.nextLine().split("=");
        first.set_account_id(Integer.parseInt(a[1].trim()));

        a = scan.nextLine().split("=");
        first.set_name(a[1].toUpperCase().trim());

        a = scan.nextLine().split("=");
        first.set_address(a[1].trim());

        a = scan.nextLine().split("=");
        first.set_phone_number(a[1].trim());

        a = scan.nextLine().split("=");
        first.set_date_of_birth(a[1].trim());

        a = scan.nextLine().split("=");
        first.set_balance(Double.parseDouble(a[1].trim()));

        a= scan.nextLine().split("=");
        first.set_accType(a[1].trim());

        if (first.get_accType().equals("Saving")){
            first = first1;
        }

        else if(first.get_accType().equals("Checking")){

            first = first2;
        }

        else if(first.get_accType().equals("Fixed")){

            first = first3;
            a = scan.nextLine().split("=");
            first3.set_intRate(Double.parseDouble(a[1].trim()));
        }

        System.out.println(first.get_name());

        scan.nextLine();// resets the buffer reader
        review[0]= first;
        count = count+1;

        while (scan.hasNext()&& count>0){
            Customer temp = new Customer();
            Account1 temp1 = new Account1();
            Account2 temp2 = new Account2();
            Account3 temp3 = new Account3();

            String[] st = scan.nextLine().split("=");

            for(int i=0;i<count;i++){
                if(Integer.parseInt(st[1].trim())== review[i].get_accountid()){ // checking for duplicate records
                    System.out.println("This account id is already in use so the record won't be read");
                    for (int k=0; k<7; k++)
                        scan.nextLine();
                }
                else
                    break;
            }

            temp.set_account_id(Integer.parseInt(st[1].trim()));
            st = scan.nextLine().split("=");
            temp.set_name(st[1].toUpperCase().trim());
            st = scan.nextLine().split("=");
            temp.set_address(st[1].trim());
            st = scan.nextLine().split("=");
            temp.set_phone_number(st[1].trim());
            st = scan.nextLine().split("=");
            temp.set_date_of_birth(st[1].trim());
            st = scan.nextLine().split("=");
            temp.set_balance(Double.parseDouble(st[1].trim()));
            st= scan.nextLine().split("=");
            temp.set_accType(st[1].trim());

            if (temp.get_accType().equals("Saving")){
                temp = temp1;
            }

            else if(temp.get_accType().equals("Checking")){

                temp = temp2;
            }


            else if(temp.get_accType().equals("Fixed")){
                temp = temp3;
                st = scan.nextLine().split("=");
                temp3.set_intRate(Double.parseDouble(a[1].trim()));
            }

            if (scan.hasNextLine()){
                scan.nextLine();
            }

            int j;
            for(j=0;j<count;j++){

                if (temp.get_name().compareTo(review[j].get_name())<0){ // Putting records in ascending order
                    break;
                }
            }

            count=count+1;
            for (int k=count;k>j;k--){
                review[k]=review[k-1];
            }

            review[j]= temp;

            if (count>=30){
                System.out.println("The number of records read has exceeded the limit and it will stop reading now");
                break;
            }

        }

        return count;
    }
}

package lab4;

import java.io.*;
import java.util.*;
/**
 *
 * @author dawnoflife
 */
public class Account1 extends Customer {

    public Account1(){ // Savings Account
        super();
    }

    public void update(double rate){ // Savings account interest calc
        double updateBal = (this.get_balance()*( Math.pow((1+rate),31))); // Interest calculated for month of march
        this.set_balance(updateBal);
    }


}

So, you are reading the information into the Customer object in the first variable, and then you throw this away with first = first1 . (or first2 , first3 ).

Later you do the same thing with temp and temp1 (or temp2 , temp3 ).

I think you misunderstood the meaning of the = operator. It does not change the class of the existing first object to the class of first1 , but it switches the pointer in the variable from the existing object to another object.

Before:

             .------------.
first -----> | Customer   |
             '------------'

             .------------.
first1 ----> | Account1   |
             |            |
             '------------'

After:

             .------------.
first        | Customer   |
    \        '------------'
     \
      \      .------------.
       '---> | Account1   |
first1 ----> |            |
             '------------'

All the information in the Customer object is now away. (The same applies in the other account types, and for temp later.)

It looks like you have to do one of these:

  • When deciding which account type to use, you have to copy the data to your account.

    You could use a copy constructor for this.

  • change your file format to contain the account type first, and create an object of the right type at the start.


By the way, think about the design - why is Account1 a subclass of Customer ? A customer is not an account, he has one .

So better use delegation here, and think about which part of the information is part of the account, and which is part of the customer. Then one customer could even have multiple accounts (of different types, even).

Your code is quite hard to read. One of the problems you are having is because you are losing information you've set using the methods of an object when you then re-assign a different value to that object.

Please see my answer to inheritance and polymorphism java which I believe will help you solve this.

What you are trying to do is build up Customer objects of type Account1, Account2, Account3, based on some value you have parsed in from scanning a file. The FIRST thing to do is to construct the correct type of object. THEN set the values in the methods specific to that type. Then set the values in the methods that are in the super class, Customer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM