Java Homework Help (Accessing Static Member via Instance Reference)

Bit Deception picture Bit Deception · Aug 20, 2013 · Viewed 20.9k times · Source

Here is my homework question:


Write a class declaration for a class “Clock”. It should have instance variables for hours, minutes, seconds (all integers). It should also have a toString() method to show the time in the format shown below. Write a separate “ClockDriver” class to a) create an instance of a clock, b) set the hours, minutes, and seconds for the clock, and c) show the time of the Clock using getTime(). Use the Dog class example on page 36 as a guide. Sample out is shown below:

The time is 3:45:00

// don’t worry if you can’t get both zeros in

// the second field. That is a formatting issue

// we will deal with later


Here is my Clock class:

class Clock  {

int hours;
int minutes;
int seconds;


public String toString() {

    String temp = ("");
    return temp.format("%02d:%02d:%02d", hours, minutes, seconds);

} //end method toString

public void getTime() {

    System.out.print("The time is " + toString());

} //end method getTime

} //end class Clock

And here is my ClockDriver class:

public class ClockDriver {

    public static void main (String[] args) {

        Clock c = new Clock();
        c.hours = 4;
        c.minutes = 30;
        c.seconds = 00;
        c.getTime();

    } //end main

} //end class ClockDriver

Even though it compiles fine and works nicely, I get what I think is a warning from IDE saying that my

return temp.format("%02d:%02d:%02d", hours, minutes, seconds);

line is accessing a static member via instance reference. Specifically, the

temp.format

bit.

So my questions are:

1.) Why is accessing a static member via instance reference not necessarily encouraged?

2.) Is there a better way to put this together so that I'm not accessing a static member via instance reference?

Thanks in advance!

Answer

rgettman picture rgettman · Aug 20, 2013

Static methods belong to the class itself, not any instance. While you can call a static method from an instance of the class, you don't have to use an instance of the class, and you should not. It can be confusing, because it looks like the method is not static, even though it is static.

The best and clearest way to call a static method is to use the class name itself, not an instance of the class, to call the method:

return String.format("%02d:%02d:%02d", hours, minutes, seconds);

And you don't need the temp instance at all.