Sub class and super class
I am trying to learn more about sub classes and super classes. I understand the sub class extends the superclass and is thus derived from the super class.
So is it true to say that a sub class is then a subset of a super class?
I also understand that if a subclass does not define a constructor it invokes the constructor of the super class but is that always the case? Or is that only when there is not a sub class constructor defined?
Re: Sub class and super class
Quote:
Originally Posted by
dragstang86
...So is it true to say that a sub class is then a subset of a super class?
No. A sub class does not have the super class's private fields and methods, but it has all the public and protected fields and methods and often a few of its own fields and methods.
Quote:
I also understand that if a subclass does not define a constructor it invokes the constructor of the super class
A sub class always invokes the super class constructor, always, either explicitly or implicitly.
Re: Sub class and super class
Thank you. Just to make sure I am understanding correct. To invoke the constructor explicitly would be to call super() and to invoke it implicitly would be simply to just do nothing?
Re: Sub class and super class
Quote:
Originally Posted by
dragstang86
Thank you. Just to make sure I am understanding correct. To invoke the constructor explicitly would be to call super() and to invoke it implicitly would be simply to just do nothing?
Correct. When you call it explicitly, you can choose which constructor to call, the default one with no parameters or one with one or many parameters. If you do nothing, the default constructor is always called. This can cause a compiler error if no default constructor is available in the super class.
Re: Sub class and super class
Ok that makes sense. What are the requirements for defining a constructor within the subclass? Playing around with it in the IDE I can only get classes to compile if either there is no constructor defined in the subclass or if both the superclass constructor and subclass constructors have no arguments.
Re: Sub class and super class
Code:
public class MyParent {
public MyParent(int someParameter) {
}
}
....
public class MySub extends MyParent {
public MySub(int someParameter) {
super(someParameter); // Works as there is a constructor that takes an int argument in the parent.
}
public MySub() {
super(1); // Works as there is a constructor that takes an int argument in the parent.
}
public MySub() {
super(); // Doesn't work as there is no constructor that takes no parameters.
}
public MySub() {
// Doesn't work for the same reason.
}
}