h-h-h-h
h-h-h-h

Reputation: 1

How do I access the variables of a subclass in java?

In my program I have a User class and two subclasses Customer and Seller. At the start of the program I keep track of the user (Customer or Seller) that is currently logged in through an authUser variable. The issue I have is that in a separate method I have to access a variable in authUser that is specific to the Customer class and is not present in the User class. How would I go about accessing it because it shows an error if I try to get the variable since technically authUser was declared as a User type and not a Customer type. I've tried checking the instance of authUser to see if they are a Customer or Seller and casting the variable accordingly but that did not work.

Edit: My bad, I didn't realize how vague it was. the code is setup like below

My issue is that authUser.variableINeed is not being recognized because variableINeed is not part of the User class even though authUser could contain a Customer object.

    public class User {
        String user;
        String pass;
    }
    
    public class Customer extends User{
        LinkedList<> variableINeed;
    }
    
    public class Seller extends User{
        //other irrelevant info
    }

    public class Implementation(){
        public static void main(String[] args){
            //calls a login() function which initializes authUser to either a Customer or Seller object based on who logs in
            //method that needs authUser.variableINeed
        }
        User authUser;
    }

Upvotes: 0

Views: 112

Answers (2)

Daniel
Daniel

Reputation: 1460

If I understood your problem correctly, then you have to cast the User object to the Customer:

User authUser = /* ... */;

// in your method:
// Check if the logged-in user is a customer
if (authUser instanceof Customer) {
  // Cast the authUser object to a Customer
  Customer customer = (Customer) authUser;
  // Now you can access the attributes of the `Customer` class from the customer object
  System.out.println(customer.customerAttribute);
}

Upvotes: 1

Vincent
Vincent

Reputation: 166

It's kind of hard to understand what you're saying without snippets. You said the authUser is specific to the Customer class and not present in the User class, but also authUser was declared as a user type. I'll assume they're in both but you want to access the parent class's snippet. You can reference it using the super keyword. Reference: https://docs.oracle.com/javase/tutorial/java/IandI/super.html

Upvotes: 2

Related Questions