继承和多态java [英] inheritance and polymorphism java

查看:52
本文介绍了继承和多态java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有基类、客户和子类 Acc1,直到 3.

当我读取一个文件来初始化我的客户对象数组时,它们都显示为空.当我找出客户的帐户类型时,我将变量分配给相应的对象(temp1-3,first1-3).不太清楚为什么它们仍然是空的.

我正在粘贴基类和派生类之一的类定义.当我将 first 和 temp(Customer class objects_ to first(1/2/3) and temp(1/2/3) (sub classes, Account1, Account2 and Account3) 分配给 readFile() 方法时,错误发生在 readFile() 方法中.

不确定类定义是否错误,因为我只是在所有类中调用了超级构造函数.尝试调试它但没有成功.将不胜感激.

package lab4;导入 java.io.*;导入 java.util.*;公开课实验室4{静态整数计数=0;//读取或写入的记录数公共静态无效主(字符串参数[])抛出 IOException{客户[]记录=新客户[30];for (int j=0; j<30; j++){记录[j] = 新客户();}菜单(记录);}public static int readFile(String filename, Customer[] review)抛出 IOException{Scanner scan = new Scanner (new File (filename));/*单独读取第一条记录*/客户至上 = 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")){第一个=第一个;}否则 if(first.get_accType().equals("Checking")){第一个 = 第 2 个;}else if(first.get_accType().equals("Fixed")){第一个 = 第 3 个;a = scan.nextLine().split("=");first3.set_intRate(Double.parseDouble(a[1].trim()));}System.out.println(first.get_name());scan.nextLine();//重置缓冲区读取器评论[0]=第一;计数=计数+1;而 (scan.hasNext()&&count>0){客户临时 = 新客户();Account1 temp1 = new Account1();Account2 temp2 = new Account2();Account3 temp3 = new Account3();String[] st = scan.nextLine().split("=");for(int i=0;ij;k--){评论[k]=评论[k-1];}评论[j]= 温度;如果(计数> = 30){System.out.println("读取的记录数已超过限制,停止读取");休息;}}返回计数;}}包 lab4;导入 java.io.*;导入 java.util.*;/**** @作者黎明生命*/公共类 Account1 扩展客户 {public Account1(){//储蓄账户极好的();}public void update(double rate){//储蓄账户利息计算double updateBal = (this.get_balance()*( Math.pow((1+rate),31)));//计算三月份的利息this.set_balance(updateBal);}}

解决方案

因此,您将信息读入 first 变量中的 Customer 对象,然后您用 first = first1 扔掉它.(或first2first3).

稍后您对 temptemp1(或 temp2temp3)做同样的事情.>

我认为您误解了 = 运算符的含义.它不会将现有first 对象的类更改为first1 的类,而是将变量中的指针从现有对象切换到另一个对象.

之前:

 .------------.第一 ----->|客户 |'------------'.------------.第一 ---->|帐号 1 |||'------------'

之后:

 .------------.第一 |客户 |\'------------'\\.------------.'--->|帐号 1 |第一 ---->||'------------'

Customer 对象中的所有信息现在都消失了.(这同样适用于其他帐户类型,以及稍后的 temp.)

看来您必须执行以下操作之一:

  • 在决定使用哪种帐户类型时,您必须将数据复制到您的帐户中.

    您可以为此使用复制构造函数.

  • 首先更改您的文件格式以包含帐户类型,然后在开始时创建一个正确类型的对象.

<小时>

顺便想想设计——为什么Account1Customer的子类?客户不是帐户,他拥有.

所以这里最好使用委托,想想哪一部分信息是账户的一部分,哪一部分是客户的一部分.那么一个客户甚至可以拥有多个帐户(甚至不同类型).

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).

这篇关于继承和多态java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆