lundi 1 juin 2015

looping over different objects (that extends common super class) in one collection of superclasses

I struggle with inheritance in java. I have many elements that have similar properties like f.e. id,name or date. This elements have also specified parameters that belongs only to them, for example: email, address.

I would like to keeps this different elements in collection. And then display them in console, using loop. But when I put element like email (which is specified for concrete class User) it gives me an error:

value email is not a member of Person

Here is code:

public class Person {
  int id;
  String name;
  Date date;
}
public class User extends Person {
  String email;
  String login;
  String password;
}
public class Contact extends Person {
  Address address;
}

public class Customer {
  List<Person> persons;

  // AND NOW I WOULD LIKE TO PRINT THIS
  public void print() {
    for(Person person: this.persons) {
      System.out.println(person.id + " " + person.email);
    }
  }
}

I have many many similar problems with inheritance in Java. I don't know how to carry on with it? How to implement classes, that I could make it work.

Can You give me some good Design Pattern or clues?

Aucun commentaire:

Enregistrer un commentaire