Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Arrays Gotchas and Wins Adding and Removing Items Means Copying

disheng wang
disheng wang
5,422 Points

Class and Object understanding!

Hello, I am confuse of class and object relationship. When we create a class and use it in the main method, we need to create the object before we can use the class properties(method). For example:

class Bike{
/// some code here
}; 

Bike bike = new Bike();
String height = bike.getHeight(2);

However, when we import the class from written class by other for example:

import java.util.Arrays;

Arrays.copyOf(...); // we can use the class directly, and we do not need to create object 
                              // before we use its methods. Why?

May someone explain this to me please, thank you!

2 Answers

michaelcodes
michaelcodes
5,604 Points

Hi there! This is because for the Arrays class they are a static methods. When a method or variable is defined as static, it is called directly from the class without creating an object. The first example you used of a Bike class would be non-static.

Static members are generally used when something is "true of all (object)"

An example of using static members would be, say you had a class called Battery, and for all batteries the max charge was 100, and some other method called discardBattery that was static, You could declare the variable\method as such:

public class Battery {
     public static final int MAX_BATTERY = 100; //final making it a constant

public static void discardBattery() {
//some code here
      }
} 

These would be accessed through the following:

Battery.MAX_BATTERY; //to retrieve the 100
Battery.discardBattery(); //to run our static discard battery method

So we can see it does not have to do with whether or not it was imported, but rather whether it is static or non-static.

Hope this helps! happy coding!

Also declaring static means that you put the class into stored memory and therefore have to declare static for any method or create a new object then use a method or variable that isn't declared static.