简体   繁体   中英

How can I access an object within another object's method?

I am a (very) amateur Java programmer and I am having some trouble. Essentially, I have 2 classes: A and B, where B extends A.

In A, I have a method defined that creates some ZonedDateTime objects. I know how to create an instance of A in B so that I can execute A's method in B, but the problem lies later on when I need direct access to that method's ZonedDateTime objects. My first guess was to access them like this:

// Assuming the ZonedDateTime objects, e.g. dateTimeA, are within ClassA's "methodA()" method...
ClassA objectA = new ClassA();
System.out.println(objectA.methodA().dateTimeA);

When this inevitably errored, I figured I would need the method to return the objects, but from what I can tell, this is not possible; you can return only certain data types, not objects. I should also mention that I need the objects to remain as objects, so converting them to Strings then returning them that way is not going to work for me.

This issue feels very basic, but even so I couldn't find any answers elsewhere; I'm sorry if this is a duplicate question. Any help would be greatly appreciated.

EDIT(S):

Here is more of my code to make the problem more reproducible:

WatchFaceEDIT (ie A):

import java.time.ZonedDateTime;
import java.time.ZoneId;
    
public class WatchFaceEDIT {
    
    // Up here are some variable declarations and things used in the switch statement below.
    
    public void watchFaceMethod(String userInput) { // userInput is a parameter passed up from a subclass of this class.
        
        switch (userInput) {
            case "1":
            ZonedDateTime dateTimeHere = ZonedDateTime.now();
            hour = dateTimeHere.getHour();
            minute = dateTimeHere.getMinute();
            amPM = dateTimeHere.getHour();
            break;
            
            case "2":
            ZonedDateTime dateTimeThere = ZonedDateTime.now(ZoneId.of("Europe/Paris"));
            hour = dateTimeThere.getHour();
            minute = dateTimeThere.getMinute();
            amPM = dateTimeThere.getHour();
            break;
            
            case "3":
            hour = -1;
            minute = -1;
            break;
        }
        // The rest of the code in WatchFaceEDIT does some things with these hour and minute variables.
    }
}

WatchEDIT (ie B):

import java.time.format.DateTimeFormatter;

public class WatchEDIT extends WatchFaceEDIT {
    
    static void watchMethod(String userInput) {

        WatchFaceEDIT watchFaceObject = new WatchFaceEDIT();
        watchFaceObject.watchFaceMethod(userInput);

        DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("hh:mm a 'on' EEEE, MMMM dd, yyyy");
        String dateTimeDisplay = watchFaceObject.watchFaceMethod(userInput).dateTimeHere.format(dateTimeFormat);
        // There is more to the code than this, but the problem seems to be here.
    }
}

I will briefly mention here that I thought the problem could have to do with the scope of the switch statement, but in WatchEDIT I was able to run watchFaceMethod without problems, and the method does utilize the created objects to display things.

I checked your initial post to get more into the context and I'd suggest more suitable refactoring:

  1. You should not use static for watchMethod in WatchEDIT - then you'll be able to refer members of its superclass
  2. Move printing functionality in WatchFaceEDIT to separate method
  3. Set all relevant values in WatchFaceEDIT::watchFaceMethod

That being said, the code fixes are as follows:

public class WatchFaceEDIT {
    // instance variables set inside watchFaceMethod
    protected int hour;
    protected int minute;
    protected int amPM;
    protected ZonedDateTime dateTimeObject;

    public void watchFaceMethod(String userInput) {
        
        switch (userInput) {
            case "1":
                dateTimeObject = ZonedDateTime.now();
                hour = dateTimeHere.getHour();
                minute = dateTimeHere.getMinute();
                amPM = dateTimeHere.getHour();
                break;
                
            case "2":
                dateTimeObject = ZonedDateTime.now(ZoneId.of("Europe/Paris"));
                hour = dateTimeThere.getHour();
                minute = dateTimeThere.getMinute();
                amPM = dateTimeThere.getHour();
                break;
                
            case "3":
                dateTimeObject = null;
                hour = -1;
                minute = -1;
                amPM = -1;
                break;
        }
        printSomething();
    }
    
    public void printSomething() {
        // move here the printing code from watchFaceMethod
        // if needed you may override this method in WatchEDIT class to modify display
        // The rest of the code in WatchFaceEDIT does some things with these hour and minute variables.
    }
}

public class WatchEDIT extends WatchFaceEDIT {
    
    public void watchMethod(String userInput) {
        // call method defined in super class and set instance variables
        watchFaceMethod(userInput);
        
        DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("hh:mm a 'on' EEEE, MMMM dd, yyyy");
        
        String dateTimeDisplay = dateTimeObject == null ? "N/A" : dateTimeObject.format(dateTimeFormat);
        
        // There is more to the code than this, but the problem seems to be here.
    }
}

Main class just creating an instance of subclass

// does not need to extend WatchEDIT/WatchFaceEDIT classes
public class Main {
    public static void main(String[] args) {
        
        WatchEDIT watchObject = new WatchEDIT();

        System.out.println("Welcome to Interactive Watch!\n");
        System.out.println("What would you like to do?");
        System.out.println("[1] See local time.");
        System.out.println("[2] See local time in a particular place.");
        System.out.println("[3] See something special.\n");
        
        Scanner scannerObject = new Scanner(System.in);
        
        boolean loopBreak = true;
        
        while (loopBreak) {
            
            loopBreak = false; // loopBreak set to false
            
            String userInput = scannerObject.nextLine(); // User inputs some string
            
            switch(userInput) {
                case "1":
                case "2":
                case "3":
                    watchObject.watchMethod(userInput);
                    break;
                
                default:
                    loopBreak = true; // loopBreak set to true; while loop reinitiates
                    System.out.println("\nPlease enter a valid key.\n");
                    break;
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM