Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Objects Harnessing the Power of Objects Constants

mohamadreza azadi
mohamadreza azadi
5,167 Points

static keyword

i'm so confused to static keyword : static keyword never needs to define keyword new right? but why we used this keyword ? for what? please help me

Quinton Rivera
Quinton Rivera
5,177 Points

It allows you to use a method of class with creating an object of the class.

You can just use the method because it represents the value of the entire class.

Its like if you birds maybe 10 of them, instead of counting them, if you have a static variable, you can just call that static variable to find out the total number of birds instead of calling them, static variables keep track of class objects.

2 Answers

Thomas Nilsen
Thomas Nilsen
14,957 Points

One example would be if you want to store a value across several instances. Here is an example:

class Person {
    public static int numberOfPeople = 0;
    private String name;

    {
        numberOfPeople++;
    }

    Person() {
        this.name = "Default Name";
    }

    Person(String name) {
        this.name = name;
    }

}


class Test {
    public static void main(String[] args) {
        Person p1 = new Person("Mark");
        Person p2 = new Person("Joe");
        Person p3 = new Person();

        //This will print 3
        System.out.println(Person.numberOfPeople);
    }
}

A static keyword can be used outside of the class it was defined in.

Obviously but mohammedreza wanted another useful purpose of the Static Keyword.