Over 10 Million Study Resources Now at Your Fingertips

Download as :
Rating : ⭐⭐⭐⭐⭐
Price : $10.99
Pages: 2

There only one count variable since static

Applying Access Modifiers 183

One more time because this is really important: what does the following output?

The following is a common mistake for rookie programmers to make:

public class Static {
private String name = "Static class";
public static void first() { }
public static void second() { }
public void third() { System.out.println(name); } public static void main(String args[]) {
third(); // DOES NOT COMPILE
} }

TA B L E 4 . 3 Static vs. instance calls



Using the classname

Static method


Instance method

A static method or variable

Instance method

Another instance method Yes
Using a reference variable

Lines 3 and 4 are fi ne because both static and instance methods can refer to a static variable. Lines 5–8 are fi ne because an instance method can call a static method. Line 11 doesn’t compile because a static method cannot call an instance method. Similarly, line 14 doesn’t compile because a static variable is trying to use an instance variable.

A common use for static variables is counting the number of instances:

How It Works
Login account
Login Your Account
Add to cart
Add to Cart
Make payment
Document download
Download File
PageId: ELIE0DC838
Uploaded by :
Page 1 Preview
there only one count variable since static
Sell Your Old Documents & Earn Wallet Balance