Unit Score Homework and Notes
6 0.9 link
7 0.95 link
8 1.1 link
9 0.95 link
10 0.95 Was MC submitted on google form

Overall: 5.85/6

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.

Inheritance and Extends with Examples of Subclass and Super Keyword

Inheritance in Java is the method to create a hierarchy between classes by inheriting from other classes.

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;
	}

}

Access Modifiers

  • Restrict the scope of a class, constructor, variable, method, or data member.
  • Types: default, private, protected, and public.
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;
    }
  }