Subclasses
A square is a rectangle
Two principles of OOP, polymorphism and inheritance are applied in Java through the use of subclasses. Inheritance means that classes can inherit the methods and properties of other classes. This is exactly what a subclass does. Polymorphism means "many forms". In OOP, this means that subclasses can override methods in its superclass, allowing one method to preform different tasks depending if it is called by a subclass or superclass. An object of a subclass can also be assigned to a variable of its superclass.
Creation
To create a subclass, we need to use the extends keyword in the declaration of the class. Methods and fields of the superclass will be automatically inherited if they are declared protected or public. See the example on the right.
public class MyClass extends MyClass2{ // fields and methods}Overriding
To follow the principle of polymorphism, methods in the superclass can be overridden. To do this, we just write a method with the same declaration as the method we want to override. To call methods from the superclass, we use the super keyword (super.method()). The constructor can be called in the subclass constructor by just calling super().
public class Point{ // a point on a cartesian plane // fields protected int x; // the location on the x axis protected int y; // the location on the y axis // methods Point(int x, int y){ this.x = x; this.y = y; } int dist(){ // manhattan distance return x+y; }}public class ProjectedPoint extends Point{ //point but coords are mutiplied by z // fields private int z; // scale // methods public ProjectedPoint(int x, int y, int z){ // override super(x,y); // call super constructor this.z = z; } int dist(){ // override return super.dist()*z; }}Abstract Classes(another one)
Abstract classes are classes that are made to be a superclass. You cannot directly make instances of abstract classes, but you can assign an instance of a subclass to an object of the abstract class. You use the abstract keyword to make a class abstract. In the abstract class, methods can be either fully written out, or just declared abstract so that it is supposed to be implemented in subclasses. When a method is declared abstract, it has no body.
public abstract class MyClass{ // fields // methods public abstract void method(); // abstract method example}