Review java - OO
Class & Object
A class only exists at compile time;
An object only exists at runtime.
Data Encapsulation
Data Encapsulation/information hiding: where the internal state and operation are hidden from others.
The more information Class A knows about Class B, the greater the possibility that changing Class A will adversely affect Class B. In an ideal world, making internal changes to Class A should have no, or very little, effect on other classes.
Access control allows for encapsulation
Access modifiers
Qualifier | class | package | subclass | outside the package |
---|---|---|---|---|
public | √ | √ | √ | √ |
protected | √ | √ | √ | X |
default | √ | √ | X | X |
private | √ | X | X | X |
Instance variable & Local variable
Instance variable is declared inside a class but not inside a method.
Local variable is declared within a method.
Getter & Setter
If a instance variable is private, constructor should use the setter of that variable.
Wrong code
|
|
Test code:
|
|
Change constructor into:
|
|
Method overloading
Whenever two or more methods have the same name but different input parameters.
Write a java class
Instance variable
Constructors
Accessors(getter)
Mutator(setter)
Service Methods
toString() method
With the toString() method, the object can be printed with a user-defined format.
1 2 3
public string toString(){ return "< user-defined format"; }
A test class