Wednesday, August 26, 2009

How to call constructor of SuperClass

Inheritance is the core concept of Object oriented programing and Java programming Language.Since every subclass has exclusive rights to use the every resource of its superclass.Constructor of superclass holds important position in this regard.There are many functions a subclass can import by calling the constructor of its superclass.The call to the Superclass constructors can be made by using the ' super ' keyword.The main points to remembered in case of using super keyword are as follows:-

1.The default Constructor of the superclass is invoked even if the super() method is not called in the subclass.It is also invoked if you do not pass any arguments to super().If the default constrictor is not available,compiler generates an error.

2.You can invoke a special constructor of the superclass by passing arguments to the super method,if the constructor is overloaded in the superclass.

3.The super() method must be the first statement in the constructor of the subclass.

Lets take a look at following example:- The example illustrates how you can call a super class constructor.

The Superclass

class Car
{
Strring Name;
int seats=4;

Car(){
.....
}

Car(int seats,String Name){
....
}
}

Subclass which invokes the superclass constructor

public class Subaru extends Car{
int wheels;

public Subaru(){
super(4,"Subaru Impreza");
wheels=4;
}
}

Here the constructor of superclass is invoked by the method call super(4,"Subaru Impreza") and you can call the default constructor by placing your call super().By following the way you can invoke the superclass constructor which can be helpful in many tasks in your application.

Useful Links:-
Why Java Classes not marked final
Why code reuse is exclusive feature of Java
Polymorphism in Java
Why Java not support multiple inheritance
Inheritance Complete explanation
Is a and Has-a relationship

Sponsored Links:-

Are you Intelligent Check here
Get your Copy of SCJP kit Free !!!!!

0 comments:

About This Blog

This Blog is all about Java and programming.This blog is written by Vaibhav Pandey .He is a Computer Science Graduate .You can contact the author at javatute@gmail.com for any suggestion or Query.You can also contact the author for advertising on this blog.All the material presented here is the property of author and its reproduction in any form is strictly prohibited.

Disclaimer:-Download links provided here are not of author in any means.These are found over the Internet.
Page copy protected against web site content infringement by Copyscape

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP