o Common attributes and behaviors of related classes into a single class called a superclass.
o Classes extend a superclass
▪ Known as subclasses
● Keyword Extends
o Creating an inheritance relationship
● Class extends only one superclass.
● Multiple subclasses can extend a superclass.
● Subclass to superclass relationship
o Forms a is-a relationship
● Subclasses inherit private instance variables from the superclass.
● Constructors can’t be inherited.
● Instance variables are initialized from the parameters passed in the superclass from which we called the constructor.
● Superclass constructors continue until an Object constructor is called.
o Doesn’t matter whether it’s called implicitly or explicitly.
● Example (part 1)
class Human
{
private String name;
public Human(String theName)
{
this.name = theName;
}
public String getName()
{
return name;
}
public boolean setName(String newName)
{
if (newName != null)
{
this.name = newName;
return true;
● Example (part 2)
}
return false;
}
}
public class Employee extends Human
{
private static int nextEmployeeId = 1;
private int employeeId;
public Employee(String theName)
{
super(theName);
employeeId = nextEmployeeId;
nextEmployeeId ++;
}
public int getEmployeeId()
{
return employeeId;
}
public static void main(String[] args)
{
Employee emp = new Employee("Ella");
System.out.println(emp.getName());
System.out.println(emp. getEmployeeId ());
}
}
● Overriding methods
o Methods in a subclass have the same method signature.
● Overloading methods
o Multiple methods have the same name but different parameter types
o Different order of the parameters
o OR the number of parameters are different
● Two uses of the keyword super
o super();
o super(arguments);
o super.method();
▪ Calls the superclass method but not the constructors from the class.
● Inheritance Hierarchy
o Subclass inheriting from a superclass
o Formed with an object
o Objects at the top of the hierarchy
o Methods in the declared type
o Determines the accuracy of a non-static call
o Methods in the object type
o Implemented for a non-static call
o Known as polymorphism
● Object Class is superclass of all classes in Java
o In the built-in java.lang package
● These are two Object class methods and constructors
o String toString()
o boolean equals(Object other)
● Subclasses of Object can override these methods with implementations that are specific to the class.