So, we can classify digital objects by designing class files!
We can determine the properties (attributes/variables) associated with the class.
We can also define behaviours (methods) that can access (get) and mutate (set) the values of the properties.
In this example, we are defining what a digital Chicken is like. Some Chickens lay eggs, some don't.
public class Chicken{
private boolean eggLayer; //eg true or false
private String name; //eg Titan
private double weightInGrams; //eg 120.5
//constructor method
public Chicken(boolean eggLayer, String name, double weight){
this.eggLayer = eggLayer;
this.name = name;
this.weightInGrams = weight;
}
//accessor methods
public boolean getEggLayer(){
return this.eggLayer;
}
public String getName(){
return this.name;
}
public double getWeight(){
return this.weightInGrams;
}
//mutator methods
public void setEggLayer(boolean layerStatus){
this.eggLayer = layerStatus;
}
public void setWeight(double newWeight){
this.weight = newWeight;
}
}
So, we can see that everything we need to know about Chicken objects is defined in the Chicken class.
The class includes both:
Encapsulation is when properties and methods are stored in a single class file.
Data hiding is also part of encapsulation - data can only be accessed and changed via methods
Attempt the Dragon Project in the Exercises tab. Keep in mind the concepts covered so far:
When designing a class, identify the attributes/properties that each instance of that class will have eg name, score.
Use data hiding! This will only allow access to class attributes via secure methods...
Design a constructor method which will usually initialise class attributes.
Design accessor methods to allow other classes access to the attributes of the class you are designing.
Design mutator methods to allow other classes an opportunity to edit/modify data stored in the attributes of the class you are designing.
Test your design by creating instances of the class in a Main program!
idesyntax file class instantiate constructor type propertymethod