A. Notes
As mentioned in the four principles of OOP, we need to keep all instance variables private, and use public methods to access or update their values. i.e. the code in bold below is not recommended, we used this only to explain how objects are created.
class Main {
public static void main(String[] args) {
Fish a = new Fish();
a.colour="red";
a.price = 8;
System.out.println(a.isPopular());
}
}
public class Fish {
String name;
String colour;
String weight;
int lifespan;
String watertype;
double price;
public boolean isPopular(){
if(price>5 && price <10 && (colour.equals("red")|| colour.equals("orange"))){
return true;
}
else return false;
}
}
2. In reality, we make all instance variables private, and define public methods called getters and setters to access or change the private variables as necessary. Sometimes we use the name "accessors" and "mutators" to refer to the methods that retrieve private variables and change the private variables.
class Main {
public static void main(String[] args) {
Fish a = new Fish();
a.setColour("red");
a.setPrice(8);
System.out.println(a.isPopular());
}
}
public class Fish {
private String name;
private String colour;
private String weight;
private int lifespan;
private String watertype;
private double price;
public void setColour(String newColor){ colour = newColour;}
public String getColour(){ return colour;}
public void setPrice(double newPrice){ price = newPrice;}
public String getPrice(){ return price;}
...
public boolean isPopular(){
if(price>5 && price <10 && (colour.equals("red")|| colour.equals("orange"))){
return true;
}
else return false;
}
}
B. Summary:
from now on, all instance variables have to be declared as private, public accessors and mutators have to be provided.
static variables may be public or private. If they are private, public accessors and mutators have to be provided as static methods.
C. Exercise
Change all instance variables in Student, Fish, Car, Book, Table, CreditCard class to private
Provide public mutators and accessors to each private instance variables