Inheritance is used when you have a class that's a more specific category of a more general class. The more specific class (the subclass) will inherit from the more general class (the superclass), meaning the child class will have all of the methods and instance fields of the parent class. The child class can add its own instance fields and methods.
Here's an example of the syntax:
public class Square extends Rectangle
The keyword extends is used for inheritance. Also note that a Square is a Rectangle with some more specific requirements. Square will inherit all of the methods and instance fields of the Rectangle class and maybe add a few of its own. Note that inherited instance fields are private, so a subclass cannot access them, but methods are public. As always, we find our way around private instance fields with public methods (encapsulation).
You can override methods by creating a new method in the subclass with the same signature but different implementation. When an object calls that method, the subclass method will run by default. To call the superclass method, use the super keyword. For example, .getX() will invoke the subclass method, while super.getX() will invoke the superclass method. Overriding is a type of polymorphism.
A lot of times, we want to invoke the superclass constructor within our subclass constructor. We simply use:
super(parameters);
Note: this line must be the first line of the subclass constructor.
The Object class is the superclass of every Java class. One of the Object methods is .toString(), which returns the memory location of an object (which isn't that helpful for us to look at). We can override the .toString() method so it returns a useful String representation of the object.
Another Object method is .equals(obj). This returns a boolean (true if the 2 objects have the same contents, false otherwise). Note, == is used for comparing primitive types, and .equals(obj) is used for comparing objects. However, if you are comparing an object to null, use ==.
No comments:
Post a Comment