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 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.