2

I'm working on a school project and I need to create an ArrayList containing two types of objects,"managers" and "ticket salesmen",since I created an abstract class "user" and these two types extend it,I have created an ArrayList type "user" and stored both "managers" and "ticket salesmen" in it,but how do I access these two types? I can only access each element of the list as a "user",and get attributes that the abstract class has,not as "manager" or "ticket salesman".How can I get attributes of these two objects and can I identify objects type,as in which class is it an instance of?

5
  • 1
    Its much better to paste actual code than the description Commented Jun 11, 2017 at 13:33
  • I would say ask for starters why are you keeping both types toghether? What do they have in common ? Commented Jun 11, 2017 at 13:47
  • Kindly follow below link for this solution: stackoverflow.com/a/34437757/3095589 Commented Jun 11, 2017 at 14:07
  • @Antoniossss I am keeping them together because the assignment text says so,if I change something I lose points Commented Jun 11, 2017 at 14:09
  • @MilosRasevic sounds like useless assignement Commented Jun 11, 2017 at 15:55

6 Answers 6

1

you can use instanceof operator to identify the actual type of user

User obj = new Manager();
User obj2 = new SalesMan();
System.out.println(obj instanceof Manager); // true
System.out.println(obj instanceof SalesMan);// false

System.out.println(obj2 instanceof Manager); // false
System.out.println(obj2 instanceof SalesMan);// true
Sign up to request clarification or add additional context in comments.

4 Comments

... but casting is mostly only needed if the application wasn't designed well.
I agree. Using instanceOf should be avoided if possible.
@HenryMaathuis why should instanceof be avoided?
it's generally not always bad but it can be avoided if someone know things in advance , read more about it here
0

You should first check what the type is of the subclass. This can be done by using the instanceOf operator. Once you determined the subclass type, you should cast the User to that particular subclass. After casting you have access to the functionality of that certain subclass.

However note that the use of instanceOf should be avoided when possible. To avoid the use of instanceOf you could take a look at the accepted answer on this question.

2 Comments

It is not "generaly bad practice" - so your statement is wrong. It is bad to use it in given context, but not in general.
I generalized a bit too much. There are situations in which it can be useful, but indeed in the given context it can be avoided.
0

Iterate through the arrayList, check type using instanceof, then cast to use the methods and attributes. Try something like this.

for (User user : arrayList) {
    if (user instanceof Manager) {
        Manager manager = (Manager) user;
        //manager.method();
    } else if(list instanceof SalesMan){
        SalesMan salesMan = (SalesMan) user;
        //salesMan.method();
    }     
}

Comments

0

An alternative would be to get the type of class using getClass():

for (Object obj : userArrayList) {
    if (obj.getClass().equals(Manager.class)) {
      ...
    }
    if (obj.getClass().equals(Salesman.class)) {
      ...
    }
}

It should also be noted that instanceof will work also in the case of subclasses but this way, it won't.

Comments

0

Kindly follow below link for your solution:

https://stackoverflow.com/a/34437757/3095589

Might be possible it will be helpful to you...

Comments

0

While the other answers perfectly describe how to achieve what you asked for, what you seek to do is generally considered a bad practice in object oriented design for various reasons:

  1. Coupling: When your code makes decisions based on an object's type, you will have to add more conditional checks whenever you add more types, i.e. a third User type. This is bad, because it makes maintaining your code exponentially harder. When you add additional subclasses, you will have to find all the places in your code that may need special behavior. Forget to do this for even one of the mentioned places, and your code breaks.
  2. Using instanceof means you need to treat different subclasses of a superclass in different ways; so that superclass probably did not have enough shared functionality/data to be a superclass in the first place? Why store them together if they share so little characteristics?

Consider redesigning your code. If you still believe Manager and TicketSalesMan must inherit from User, and you need to perform some operation on them in an iterated loop, consider overriding a method instead of using instanceof. Look at the code below:

public abstract class User
{
    public abstract void doOperation();
}

public class Manager extends User
{
    public void doOperation()
    {
        // do stuff that managers do
    }
}

public class SalesMan extends User
{
    public void doOperation()
    {
        // do stuff that salesmen do
    }
}

public class Main
{
    public static final void main(String[] args)
    {
        ArrayList<User> users = getUsers();
        for(User u: users)
        {
            u.doOperation();
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.