Overview
Java is an Object-Oriented programming language. An object is a self-contained environment in which small programs run. These programs are called methods. Almost everything in java is an Object. The description of an Object is a Class.
Object-Oriented programming languages differ from traditional programming languages in that the language supports Inheritance: the ability of one Class to extend another. If class A extends class B, then an object created according the the description of class A will also behave according the description of class B.
Example of Inheritance
Example of Constructors
The details
The new operator applied to a class name creates an instance of the class. To do so, the class' constructor is called. Every class has a constructor. If no none is explicitly defined, the compiler adds the following default constructor:
ClassName() { super() ; }Further, each constructor begins with a call to the constructor of the immediate super class. This in turn generates a call the the immediate superclass of the immediate superclass. In summary, Object is constructed, then the subclass of Object, and so on until finally the named Class object is constructed.
The call to super is significant because it reminds us that constructors are not inherited. The default constructor of an object is that of its immediate superclass because of this super statement. If you write your own constructor and do not place super() or this() as the very first statement of the constructor, the compiler will place a super() by default.
You may overload constructors, but in that case the compiler does not provide the default constructor any longer. This combined with the default super() leads to the following common error:
class A { int i ; A (int i) { this.i = i ; } } class B extends A { }Class B cannot be instantiated because the default super() in the default constructor of B finds no matching constructor A. The constructor for B would need to be something like,
B(){ super(1); }
Instead of the super() statement, either explicit or default, the very first statement can be the this() statement. This will run an other of the class's constructors first, before the body of this constructor. In any case, super() is called exactly once, perhaps at the end of a chain of several this() statements.
The class name must occur in the constructor definition, but this is not the constructor's name - a constructor has no name.