Chapter 4 Flashcards
Access Modifiers
private
default (package private) access
protected
public
■ private: Only accessible within the same class
■ default (package private) access: private and other classes in the same package
■ protected: default access and child classes
■ public: protected and classes in the other packages
Static vs. Instance (members(fields or methods))
A static member cannot call an instance member.
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
} }
Type: Static method
Calling: Another static method or variable
Legal?
Yes, using the classname
Type: Static method
Calling: An instance method or variable
Legal?
No
Type: Instance method
Calling: A static method or variable
Legal?
Yes, using the classname or a reference variable
Type: Instance method
Calling: Another instance method or variable
Legal?
Yes, using a reference variable
Default Constructor
Every class in Java has a constructor whether you code one or not. If you don’t include any constructors in the class, Java will create one for you without any parameters. This Java-created constructor is called the default constructor. Sometimes we call it the default no-arguments constructor for clarity.
Having a private constructor in a class tells the compiler not to provide a default no-argument constructor. It also prevents other classes from instantiating the class. This is useful when a class only has static methods or the class wants to control all calls to create new instances of itself.
Overloading Constructors
You can have multiple constructors in the same class as long as they have different method signatures. When overloading methods, the method name and parameter list needed to match. With constructors, the name is always the same since it has to be the same as the name of the class. This means constructors must have different parameters in order to be overloaded.
Order of Initialization (4 rules)
- If there is a superclass, initialize it first (we’ll cover this rule in the next chapter. For
now, just say “no superclass” and go on to the next rule.) - Static variable declarations and static initializers in the order they appear in the file.
- Instance variable declarations and instance initializers in the order they appear in the file.
- The constructor.