Instance Variables and Methods #
Let’s bake cookies. The below class has two instance variables (size
and chocolateChips
) and two instance methods (yum
and printYum
):
Python | Java |
---|---|
|
|
|
|
Because these are instance variables/methods, each cookie has gets its own size
, chocolateChips
, yum
, and printYum
. Here’s an artist’s rendition of the above code:
The this
keyword is like self
in Python, and refers to the current Cookie
instance. Unlike Python, the this
keyword can be omitted, and Java will still know what you mean. Here is equivalent code for the yum
and printYum
methods:
public int yum() {
return size + chocolateChips;
}
public void printYum() {
System.out.println(yum());
}
The this
keyword is only needed if you have a local variable with the same name as an instance variable. For example, in the Cookie
constructor, size = size;
would do nothing, so this.size = size;
is necessary.
Static Variables and Methods #
Let’s add a static variable and a static method:
Python | Java |
---|---|
|
|
|
|
Unlike instance variables/methods, which are part of individual objects, static variables/methods are part of the class itself.
Static methods can not use the this
keyword, since there is no “this” object for the method to reference. The below code would not compile:
public static void printFunFact() {
System.out.println("I have size " + this.size); // error!
System.out.println("I have " + chocolateChips + " chips"); // error!
System.out.println("yum ".repeat(yum())); // error!
printYum(); // error!
}
Note that the 2nd, 3rd, and 4th lines all implicitly use this
(i.e. chocolateChips
is the same as this.chocolateChips
), so they error. However, the below code is fine:
public static void printFunFact() {
Cookie c = new Cookie(12, 0);
System.out.println("I made a sugar cookie! It has size " + c.size);
System.out.println("yum ".repeat(c.yum()));
}