Rohan G Units 6-10 Vocabulary Terms
Week 16 Units 6-10 Vocab Terms Blog
Polymorphism
- Polymorphism can be used when we have multiple classes that are related by inheritance. It is utilized when a method is implemented to perform different tasks in different classes. It essentially allows a method to take on multiple “forms” or implementations based on the specific object it is acting upon.
- Polymorphism is useful for code reusability, as it re-implements an existing class’s attributes and methods for new classes. A real life example of polymorphism could be a sport. A sport can take on different forms, as it can be soccer, basketball, baseball, etc.
public class Animal {
private String eats;
private int numLegs;
public Animal(){}
public Animal(String food, int legs){
this.eats = food;
this.numLegs = legs;
}
public String getEats() {
return eats;
}
public void setEats(String eats) {
this.eats = eats;
}
public int getNumLegs() {
return numLegs;
}
public void setNumLegs(int numLegs) {
this.numLegs = numLegs;
}
}
public class Cat extends Animal{
private String toy;
public Cat( String food, int legs) {
super(food, legs);
this.toy="String";
}
public Cat(String food, int legs, String toy){
super(food, legs);
this.toy=toy;
}
public String getToy() {
return toy;
}
public void setToy(String toy) {
this.toy = toy;
}
}
void HelloWorldDefault(){
System.out.println("Hello World");
}
public void HelloWorldPublic(){
System.out.println("Hello World");
}
private void HelloWorldPrivate(){
System.out.println("Hello World");
}
protected void HelloWorldProtected(){
System.out.println("Hello World");
}
Accessor and Mutator Methods
- instance method that gets or sets the value of a property of an object.
- Getters and setters are accessor and mutator methods to retrieve and set data of a variable, respectively
- accessors access the predetermined data
- mutators change the data to set new predetermined data
public class Person {
private String name; // private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}