Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
/**
* This simple program has one class: Bird (plus a main class)
* The Bird definition has three attributes, two overriding constructors,
* and a getter and setter for each attribute.
*
* Notice that the setter for attractiveness does a validity check
* before it sets the value. This is part of the value of getters
* and setters. They allows the object to control how its attributes are
* accessed and changed.
*
* In reality, there would be additional methods, like fly(),
* eat(), and buildNest().
* */
class Bird {
//Instance Attributes: each object has its own
private String species; // private: controlled by the object
private String colour;
private String attractiveness;
//Constructors (overloaded, without and with parameters)
public void Bird(){
species = "";
colour = "";
attractiveness = "pretty"; // default
}
public void Bird(String species, String colour, String attractiveness){
this.species = species;
this.colour = colour;
this.attractiveness = attractiveness;
}
//Getters and Setters
public String getSpecies() {
return species;
}
public void setSpecies(String species){
this.species = species;
}
public String getColour(){
return colour;
}
public void setColour(String colour){
this.colour = colour;
}
public String getAttractiveness(){
return attractiveness;
}
//The setter for attractiveness adjusts the input
public void setAttractiveness(String attractiveness){
if(attractiveness == "nice"){
this.attractiveness = "pretty";
}else{
this.attractiveness = attractiveness;
}
}
}
public class Main {
public static void main(String args[]) {
Bird myBird = new Bird();
myBird.setSpecies("Jay");
myBird.setColour("blue");
myBird.setAttractiveness("nice");
System.out.println("The bird is a " + myBird.getSpecies() + ".");
System.out.println("The bird is " + myBird.getColour() + ".");
System.out.println("The bird is " + myBird.getAttractiveness() + ".");
}
}
Advertisements
We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.
AcceptLearn more