Over 10 Million Study Resources Now at Your Fingertips


Download as :
Rating : ⭐⭐⭐⭐⭐
Price : $10.99
Language:EN
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[]) {
first();
second();
third(); // DOES NOT COMPILE
} }

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

Type

Legal?
Yes

Using the classname

Static method

No

Instance method

Yes
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
Payment
Make payment
Document download
Download File
PageId: ELIE0DC838
img
Uploaded by :
b9o6oeZQ
Page 1 Preview
there only one count variable since static
Sell Your Old Documents & Earn Wallet Balance