0

I have a homework to do and I've got some problems with downcasting. Here are my three classes.

import java.util.LinkedList;

public class Bank {

    LinkedList<Client> ListOfClients = new LinkedList<Client>();

    public void addClient(Client arg){
        ListOfClients.add(arg);
    }

    public void getClients(){
        for(Client c : ListOfClients)
            System.out.printf("Name: %s \nSurname: %s \nSocial Security: %s\n", c.name, c.surname, c.SocialSecurity);
    }
}

public class Client {
    LinkedList<Account> ListOfAccounts = new LinkedList<Account>();
    public void addAccount(Account args){
        ListOfAccounts.add(args);
    }

    public void getAccounts(){
        for(Account a : ListOfAccounts)
            System.out.printf("Number: %s\nBalance: %f\n", a.nr, a.balance);
    }

public class Person extends Client{
    protected String name, surname, SocialSecurity;

    public Person(){
        System.out.println("Type name: ");
        name = input_data();
        System.out.println("Type surname: ");
        surname = input_data();
        System.out.println("Type Social Security number: ");
        SocialSecurity = input_data();
    }

    public String input_data(){
        Scanner input = new Scanner(System.in);
        String data = input.nextLine();
        return data;
    }
}

So the problem is with my getClients method in Bank class. It says: "SocialSecurity cannot be resolved or is not a field". Same with name and surname fields. I know that i can copy those strings into Client class and the problem will be solved, but i need to do that with downcasting. I read something about RTTI, but still cannot find any solution for that problem.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
buksio
  • 1
  • 1
  • This comment is offtopic, but I cannot help writing it: variables and attributes names in Java should start with lowercase letters. Only class and interface names must start with uppercase letters – Pablo Lozano Feb 03 '16 at 14:24

2 Answers2

0

If Persons have been added to the Bank class you can try to cast your Clients back to Persons:

public void getClients(){
    for(Client c : ListOfClients) {
           if ( c instanceof Person ) {
              Person p = (Person) c;
              System.out.printf("Name: %s \nSurname: %s \nSocial Security: %s\n", p.name, p.surname, p.SocialSecurity);
         }
    }
}
StephaneM
  • 4,779
  • 1
  • 16
  • 33
0

The problem comes from your modelling: you have (bank) clients and persons. I understand that a client can be a person or (for example) an organization, but then your code won't work with an hypothetical class Organization because the don't have a social security id. or if they have then you should place that attribute in client, not in person.

If only persons have SS ids, then the solution that StephaneM provided is what you need, but if not, then move that attribute to the class Client

Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59