Related
I'm dealing with a class which extends JFrame.
It's not my code and it makes a call to super before it begins constructing the GUI. I'm wondering why this is done since I've always just accessed the methods of the superclass without having to call super();
There is an implicit call to super() with no arguments for all classes that have a parent - which is every user defined class in Java - so calling it explicitly is usually not required. However, you may use the call to super() with arguments if the parent's constructor takes parameters, and you wish to specify them. Moreover, if the parent's constructor takes parameters, and it has no default parameter-less constructor, you will need to call super() with argument(s).
An example, where the explicit call to super() gives you some extra control over the title of the frame:
class MyFrame extends JFrame
{
public MyFrame() {
super("My Window Title");
...
}
}
A call to your parent class's empty constructor super() is done automatically when you don't do it yourself. That's the reason you've never had to do it in your code. It was done for you.
When your superclass doesn't have a no-arg constructor, the compiler will require you to call super with the appropriate arguments. The compiler will make sure that you instantiate the class correctly. So this is not something you have to worry about too much.
Whether you call super() in your constructor or not, it doesn't affect your ability to call the methods of your parent class.
As a side note, some say that it's generally best to make that call manually for reasons of clarity.
None of the above answers answer the 'why'.
Found a good explanation here:
A subclass can have its own private data members, so a subclass can
also have its own constructors.
The constructors of the subclass can initialize only the instance
variables of the subclass. Thus, when a subclass object is
instantiated the subclass object must also automatically execute one
of the constructors of the superclass.
You might also want to read everything about the super keyword here or watch everything about the super keyword here.
We can access super class elements by using super keyword
Consider we have two classes, Parent class and Child class, with different implementations of method foo. Now in child class if we want to call the method foo of parent class, we can do so by super.foo(); we can also access parent elements by super keyword.
class parent {
String str="I am parent";
//method of parent Class
public void foo() {
System.out.println("Hello World " + str);
}
}
class child extends parent {
String str="I am child";
// different foo implementation in child Class
public void foo() {
System.out.println("Hello World "+str);
}
// calling the foo method of parent class
public void parentClassFoo(){
super.foo();
}
// changing the value of str in parent class and calling the foo method of parent class
public void parentClassFooStr(){
super.str="parent string changed";
super.foo();
}
}
public class Main{
public static void main(String args[]) {
child obj = new child();
obj.foo();
obj.parentClassFoo();
obj.parentClassFooStr();
}
}
It simply calls the default constructor of the superclass.
We use super keyword to call the members of the Superclass.
As a subclass inherits all the members (fields, methods, nested classes) from its parent and since Constructors are NOT members (They don't belong to objects. They are responsible for creating objects), they are NOT inherited by subclasses.
So we have to explicitly give the call for parent constructor so that the chain of constructor remains connected if we need to create an object for the superclass. At the time of object creation, only one constructor can be called. Through super, we can call the other constructor from within the current constructor when needed.
If you are thinking why it's there for a class that is not extending any other class, then just remember every class follows object class by default. So it's a good practice to keep super in your constructor.
Note: Even if you don't have super() in your first statement, the compiler will add it for you!
We can Access SuperClass members using super keyword
If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass:
public class Superclass {
public void printMethod() {
System.out.println("Printed in Superclass.");
}
}
// Here is a subclass, called Subclass, that overrides printMethod():
public class Subclass extends Superclass {
// overrides printMethod in Superclass
public void printMethod() {
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}
Within Subclass, the simple name printMethod() refers to the one declared in Subclass, which overrides the one in Superclass. So, to refer to printMethod() inherited from Superclass, Subclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following:
Printed in Superclass.
Printed in Subclass
as constructor is not a part of class,
so while calling it cannot be implemented,
by using SUPER() we can call the members and memberfunctions in constructor.
I'm dealing with a class which extends JFrame.
It's not my code and it makes a call to super before it begins constructing the GUI. I'm wondering why this is done since I've always just accessed the methods of the superclass without having to call super();
There is an implicit call to super() with no arguments for all classes that have a parent - which is every user defined class in Java - so calling it explicitly is usually not required. However, you may use the call to super() with arguments if the parent's constructor takes parameters, and you wish to specify them. Moreover, if the parent's constructor takes parameters, and it has no default parameter-less constructor, you will need to call super() with argument(s).
An example, where the explicit call to super() gives you some extra control over the title of the frame:
class MyFrame extends JFrame
{
public MyFrame() {
super("My Window Title");
...
}
}
A call to your parent class's empty constructor super() is done automatically when you don't do it yourself. That's the reason you've never had to do it in your code. It was done for you.
When your superclass doesn't have a no-arg constructor, the compiler will require you to call super with the appropriate arguments. The compiler will make sure that you instantiate the class correctly. So this is not something you have to worry about too much.
Whether you call super() in your constructor or not, it doesn't affect your ability to call the methods of your parent class.
As a side note, some say that it's generally best to make that call manually for reasons of clarity.
None of the above answers answer the 'why'.
Found a good explanation here:
A subclass can have its own private data members, so a subclass can
also have its own constructors.
The constructors of the subclass can initialize only the instance
variables of the subclass. Thus, when a subclass object is
instantiated the subclass object must also automatically execute one
of the constructors of the superclass.
You might also want to read everything about the super keyword here or watch everything about the super keyword here.
We can access super class elements by using super keyword
Consider we have two classes, Parent class and Child class, with different implementations of method foo. Now in child class if we want to call the method foo of parent class, we can do so by super.foo(); we can also access parent elements by super keyword.
class parent {
String str="I am parent";
//method of parent Class
public void foo() {
System.out.println("Hello World " + str);
}
}
class child extends parent {
String str="I am child";
// different foo implementation in child Class
public void foo() {
System.out.println("Hello World "+str);
}
// calling the foo method of parent class
public void parentClassFoo(){
super.foo();
}
// changing the value of str in parent class and calling the foo method of parent class
public void parentClassFooStr(){
super.str="parent string changed";
super.foo();
}
}
public class Main{
public static void main(String args[]) {
child obj = new child();
obj.foo();
obj.parentClassFoo();
obj.parentClassFooStr();
}
}
It simply calls the default constructor of the superclass.
We use super keyword to call the members of the Superclass.
As a subclass inherits all the members (fields, methods, nested classes) from its parent and since Constructors are NOT members (They don't belong to objects. They are responsible for creating objects), they are NOT inherited by subclasses.
So we have to explicitly give the call for parent constructor so that the chain of constructor remains connected if we need to create an object for the superclass. At the time of object creation, only one constructor can be called. Through super, we can call the other constructor from within the current constructor when needed.
If you are thinking why it's there for a class that is not extending any other class, then just remember every class follows object class by default. So it's a good practice to keep super in your constructor.
Note: Even if you don't have super() in your first statement, the compiler will add it for you!
We can Access SuperClass members using super keyword
If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass:
public class Superclass {
public void printMethod() {
System.out.println("Printed in Superclass.");
}
}
// Here is a subclass, called Subclass, that overrides printMethod():
public class Subclass extends Superclass {
// overrides printMethod in Superclass
public void printMethod() {
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}
Within Subclass, the simple name printMethod() refers to the one declared in Subclass, which overrides the one in Superclass. So, to refer to printMethod() inherited from Superclass, Subclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following:
Printed in Superclass.
Printed in Subclass
as constructor is not a part of class,
so while calling it cannot be implemented,
by using SUPER() we can call the members and memberfunctions in constructor.
class Parent {
public Parent() {
System.out.println("Parent Default..");
System.out.println("Object type : " + this.getClass().getName());
this.method();
}
private void method() {
System.out.println("private method");
}
}
class Child extends Parent {
public Child() {
System.out.println("Child Default..");
}
public static void main(String[] args) {
new Child();
}
}
When I run this code it prints the class name of "this" = Child
but the "this" object is able to call the private method of parent class why?
when you extend the class the private methods will not be inherited .but the object of the child class contains object of the parent class so when the superclass constructor is called .you are able to call the superclass private method inside the super class
First of all, when calling new Child(), since there is not a declared non-argument constructor in Child class, it will simple call super() which is invoking the Parent constructor.
Then, when executing this.getClass().getName(), here this stands for a Child instance, this is why you get "Child" as the result. Remember, Object#getClass() returns the most specific class the object belongs to. see more from here.
About why this.method() works. First, because Child extends Parent, the Child instance is also a Parent instance. The java scope modifier controls where the methods or fields can be accessed. Taking Parent#method() as the example, the private modifier indicates that this method can only be accessed (invoked) inside the Parent class. And this is exactly how you code does. it invokes the method inside the constructor of Parent class, which compiles the rule. See more about java access control from here
private has nothing to do with the actual class of the object. A private member can be accessed by any code within the same top-level class. (A top-level class is one that's not nested, which is unrelated to inheritance)
method is defined in Parent, and the call this.method() is also in Parent, so it's allowed.
A parent instance is not created here, you can confirm this using jvisualjvm in the /bin folder of your jdk installation, the child instance is not created either. Parent constructor is still invoked.
output:
Parent Default..
Object type : com.packagename.Child
private method
Child Default..
Parent constructor can be invoked by child class.
While in the constructor of parent, as Krishanthy Mohanachandran has noted above, a private method can be legally invoked.
It is abvious, you can call any private members within the class but not outside the class.
In this case it is legal. In this program first the constrctor of the Parent will be called and you can call private method within the class.
I'm dealing with a class which extends JFrame.
It's not my code and it makes a call to super before it begins constructing the GUI. I'm wondering why this is done since I've always just accessed the methods of the superclass without having to call super();
There is an implicit call to super() with no arguments for all classes that have a parent - which is every user defined class in Java - so calling it explicitly is usually not required. However, you may use the call to super() with arguments if the parent's constructor takes parameters, and you wish to specify them. Moreover, if the parent's constructor takes parameters, and it has no default parameter-less constructor, you will need to call super() with argument(s).
An example, where the explicit call to super() gives you some extra control over the title of the frame:
class MyFrame extends JFrame
{
public MyFrame() {
super("My Window Title");
...
}
}
A call to your parent class's empty constructor super() is done automatically when you don't do it yourself. That's the reason you've never had to do it in your code. It was done for you.
When your superclass doesn't have a no-arg constructor, the compiler will require you to call super with the appropriate arguments. The compiler will make sure that you instantiate the class correctly. So this is not something you have to worry about too much.
Whether you call super() in your constructor or not, it doesn't affect your ability to call the methods of your parent class.
As a side note, some say that it's generally best to make that call manually for reasons of clarity.
None of the above answers answer the 'why'.
Found a good explanation here:
A subclass can have its own private data members, so a subclass can
also have its own constructors.
The constructors of the subclass can initialize only the instance
variables of the subclass. Thus, when a subclass object is
instantiated the subclass object must also automatically execute one
of the constructors of the superclass.
You might also want to read everything about the super keyword here or watch everything about the super keyword here.
We can access super class elements by using super keyword
Consider we have two classes, Parent class and Child class, with different implementations of method foo. Now in child class if we want to call the method foo of parent class, we can do so by super.foo(); we can also access parent elements by super keyword.
class parent {
String str="I am parent";
//method of parent Class
public void foo() {
System.out.println("Hello World " + str);
}
}
class child extends parent {
String str="I am child";
// different foo implementation in child Class
public void foo() {
System.out.println("Hello World "+str);
}
// calling the foo method of parent class
public void parentClassFoo(){
super.foo();
}
// changing the value of str in parent class and calling the foo method of parent class
public void parentClassFooStr(){
super.str="parent string changed";
super.foo();
}
}
public class Main{
public static void main(String args[]) {
child obj = new child();
obj.foo();
obj.parentClassFoo();
obj.parentClassFooStr();
}
}
It simply calls the default constructor of the superclass.
We use super keyword to call the members of the Superclass.
As a subclass inherits all the members (fields, methods, nested classes) from its parent and since Constructors are NOT members (They don't belong to objects. They are responsible for creating objects), they are NOT inherited by subclasses.
So we have to explicitly give the call for parent constructor so that the chain of constructor remains connected if we need to create an object for the superclass. At the time of object creation, only one constructor can be called. Through super, we can call the other constructor from within the current constructor when needed.
If you are thinking why it's there for a class that is not extending any other class, then just remember every class follows object class by default. So it's a good practice to keep super in your constructor.
Note: Even if you don't have super() in your first statement, the compiler will add it for you!
We can Access SuperClass members using super keyword
If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass:
public class Superclass {
public void printMethod() {
System.out.println("Printed in Superclass.");
}
}
// Here is a subclass, called Subclass, that overrides printMethod():
public class Subclass extends Superclass {
// overrides printMethod in Superclass
public void printMethod() {
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}
Within Subclass, the simple name printMethod() refers to the one declared in Subclass, which overrides the one in Superclass. So, to refer to printMethod() inherited from Superclass, Subclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following:
Printed in Superclass.
Printed in Subclass
as constructor is not a part of class,
so while calling it cannot be implemented,
by using SUPER() we can call the members and memberfunctions in constructor.
The following code gives a compilation error:
class parent {
parent(int a){}
}
class child extends parent{}
Error:
Main.java:6: cannot find symbol
symbol : constructor parent()
location: class parent
class child extends parent{}
^
1 error
I was trying to do different things and found that adding a return type to the parent constructor got rid of the error!!!
class parent {
int parent(int a){}
}
class child extends parent{}
I've read that constructors should not have return type, which clearly is not correct all the times. So my question is when should we have return type for constructor?
In case 1 the child class does not have any constructor so the compiler adds a default constructor for you and also adds a call to superclass constructor. So your child class effectively looks like:
class child extends parent {
child() {
super();
}
}
the call super() looks for a zero argument constructor in the base class, since there is no such constructor you get the error.
In case 2 parent parent class does not have any constructor
int parent(int x) {} is not a constructor as it has a return type. Its just a method which has the class name. The child class does not have any constructor as well. So the compiler adds default constructor for both child and parent and also adds call to super class constructor:
class parent {
parent() {
super(); // calls Object class ctor.
}
int parent(int x) {} // not a ctor.
}
class child extends parent {
child() {
super();
}
}
On constructor not having return type
Constructor must not have a return type. By definition, if a method has a return type, it's not a constructor.
JLS 8.8 Constructor Declarations
A constructor is used in the creation of an object that is an instance of a class. [The name must match the class name, but], in all other respects, the constructor declaration looks just like a method declaration that has no result type.
On default constructors
The following snippet does give a compilation error:
class Parent {
Parent(int a){}
}
class Child extends Parent{
// DOES NOT COMPILE!!
// Implicit super constructor parent() is undefined for default constructor.
// Must define an explicit constructor
}
The reason is not because of a return type in a constructor, but because since you did not provide ANY constructor for Child, a default constructor is automatically created for you by the compiler. However, this default constructor tries to invoke the default constructor of the superclass Parent, which does NOT have a default constructor. THAT'S the source fo the compilation error.
Here's the specification for the default constructor:
JLS 8.8.9 Default Constructor
If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided:
If the class being declared is the primordial class Object, then the default constructor has an empty body.
Otherwise, the default constructor takes no parameters and simply invokes the superclass constructor with no arguments.
The following is a simple fix:
class Parent {
Parent(int a){}
}
class Child extends Parent{
// compiles fine!
Child() {
super(42);
}
}
On methods having the same name as the constructor
The following snippet DOES compile:
// COMPILES FINE!!
class Parent {
// method has same name as class, but not a constructor
int Parent(int a) {
System.out.println("Yipppee!!!");
return 42;
}
// no explicit constructor, so default constructor is provided
}
class Child extends Parent {
// no explicit constructor, so default constructor is provided
}
There is in fact no explicit constructor in the above snippet. What you have is a regular method that has the same name as the class. This is allowed, but discouraged:
JLS 8.4 Method Declarations
A class can declare a method with the same name as the class or a field, member class or member interface of the class, but this is discouraged as a matter of style.
You will find that if you create a new Parent() or a new Child(), "Yipppee!!!" will NOT be printed to standard output. The method is not invoked upon creation since it's not a constructor.
when you extend a class that does not have a default constructor, you must provide a constructor that calls that superconstructor - that's why the compilation error, which is:
Implicit super constructor parent() is undefined for default constructor. Must define an explicit constructor
when you add a return type this is no longer a constructor, it's a method, and the above does not apply
In the future read the error messages first, and try to reason (or find) what it implies.
Constructors do not have a return type. Constructors are called to create an instance of the type. Essentially what is "returned" from a constructor is an instance of that type ready for use.
constructors dont have any return type
try changing it to:
class parent
{
parent(int a){}
}
class child extends parent
{
child(int a){
super(a);
}
}
Technically, you didn't add a return type to the constructor, but changed the constructor into a method which just happened to be of the same name as the class. What you should have done was calling super(int), thus:
class parent
{
parent(int a){}
}
class child extends parent{ child(int a){ super(a); } }
Your code for child implicitly tries to do this:
class child extends parent{ child(){ super(); } }
That is, it tries to call a zero-argument constructor in parent, which obviously can't be done as it only has one constructor, which takes an int argument.
Already answered by codaddict but two comments.
By the java code convention classes should start with upper case (it also helful to add the modifier).
If you have compilation error then put it, all tough the case here was clear without it.
All you have done by adding the int is to turn the "constructor" into a method that has default visibility and then because you haven't specified a constructor, it will just add a default constructor for you at compilation time.
If you want this to compile, you will have to specify a default constructor, which is what the Child class is looking for, such as:
class parent
{
parent(int a){}
parent(){}
}
class child extends parent{}
1) It is best practice to start classes with a capital letter, and methods with a lowr case letter.
2) When you do not create a Constructor for a class, it has a default empty constructor.
3) When inheriting from a class you need to override at least one of it's constructors, and if you do not specify any, you automatically inherit the empty constructor.
The code you submitted would work if child had a constructor calling super(int i), if the parent class had no constructor (then it would have the default empty constructor) or if the parent class specifically implemented the empty constructor.
This will work.
public class Parent {
public Parent(int i) { }
public Parent() { }
}
public class Child {
}
The empty Child class behaves as if it was written like this:
public class Child {
public Child() {
super();
}
}
Constructors does not have a return type.Constructor returns an instance of the type.Constructor should have the same name as that of the class.