(1) A subclass inherits all variables and (normal) methods from its superclass:
(2) A subclass do not inherit any constructor method from its superclass:
Important note: a constructor in the subclass must invoke a constructor in the superclass -- later !
Notice that a subclass object (always) contains a superclass object:
Recall: objects are initialized using its constructor
(3) Rule: a constructor in the subclass must invoke some constructor in its superclass as its first statement:
The keyword super( ... ) is used to invoke a constructor in its superclass
public class myProg
{
public static void main()
{
NewClass a = new NewClass();
NewClass b = new NewClass(44);
}
}
|
public class NewClass
extends SomeClass
{
public NewClass()
{
super(); //Not:SomeClass()
}
public NewClass(int a)
{
super(a); //Not:SomeClass(a)
}
}
|
public class SomeClass
{
public int x;
public SomeClass()
{
x = 99;
}
public SomeClass(int a)
{
x = a;
}
}
|
DEMO: demo/04-inheritance/06-super
DEMO: trace the execution in BlueJ
(4a) Rule: if a constructor in the subclass does NOT invoke any constructor in its superclass:
Then... (can you guess what will happen ??? Remember the rules about default constructors ?
(4b) Then: the Java compiler will automatically insert the call super( ) as the first statement:
I.e.: when the first statement in a constructor is not super(...), the Java compiler will call the default constructor !
public class myProg
{
public static void main()
{
NewClass a = new NewClass();
}
}
|
public class NewClass
extends SomeClass
{
public NewClass()
{
// Java adds super()
}
public NewClass(int a)
{
super(a);
}
}
|
public class SomeClass
{
public int x;
public SomeClass()
{
x = 99;
}
public SomeClass(int a)
{
x = a;
}
}
|
DEMO: demo/04-inheritance/07-super
DEMO: trace the execution in BlueJ
Explain the compile error in this program:
public class NewClass
extends SomeClass
{
NewClass()
{ // Compile error... why?
}
}
|
public class SomeClass
{
public int x;
public SomeClass(int a)
{
x = a;
}
}
|
DEMO: demo/04-inheritance/08-quiz
There is a compile error in NewClass:
javac NewClass.java
NewClass.java:5: error: constructor SomeClass in class SomeClass
cannot be applied to given types;
{ // Compile error.... why ?
^
required: int
found: no arguments
|
Can you explain the error?
Because the constructor NewClass() does not contain any super(...) calls, Java compiler will insert super( ):
public class NewClass
extends SomeClass
{
NewClass()
{
super( ) // Inserted by "javac"
}
}
|
public class SomeClass
{
public int x;
public SomeClass(int a)
{
x = a;
}
}
|
However: there is no matching constructor ( SomeClass( )) defined in the superclass SomeClass !!! ---> Error
|
|
public class SomeClass
{
public int x;
public SomeClass()
{
x = 99;
}
public void method1( )
{
System.out.println("I am SomeClass.method1(). x = " + x);
}
public void method2( )
{
System.out.println("I am SomeClass.method2(). x = " + x);
}
}
|
|