-
constructors
this is a quick question to anyone that can help. thanks.
is it possible to call a parent constructor from within the child class,
and then overriding the parent constructor with a few more attributes?
// lets say the parent class is People, so i want to use
// the existing n and a to set the veriables in the People class
// and then also add the g variable to the object that is going to
//call this constructor.
class People
{
protected String name;
protected String Age;
People(String n, String a) //People constructor
{
name=n;
Age=a;
}
class Faculty extends People
{
private char g;
Faculty(String n, String a, char g)
{
People(n,a);
Gender=g;
}
// thanks
-
Re: constructors
Maz,
Yep, just swap
People(n, a);
for
super(n, a);
The keyword super, in this context, allows you to invoke the parent's constructor.
It must appear before any other code in the constructor (ensuring that the
parent object is constructed before the child).
A call to super() is mandatory for every constructor in every class except
Object. If you do not explicitly call super() the constructor inserts
super();
for you. This implies that the class you're extending must have a no argument
constructor. If your code below is complete (ie. People does not have a no
argument constructor) then you would not be able to compile without an explicit
call to super(String, String).
Hope this helps,
Kent
"maz" <mazenalie@yahoo.com> wrote:
>
>this is a quick question to anyone that can help. thanks.
>is it possible to call a parent constructor from within the child class,
>and then overriding the parent constructor with a few more attributes?
>
>// lets say the parent class is People, so i want to use
>// the existing n and a to set the veriables in the People class
>// and then also add the g variable to the object that is going to
>//call this constructor.
>class People
>{
> protected String name;
> protected String Age;
>
> People(String n, String a) //People constructor
> {
> name=n;
> Age=a;
>}
>
>class Faculty extends People
>{
> private char g;
> Faculty(String n, String a, char g)
> {
> People(n,a);
> Gender=g;
> }
>// thanks
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Development Centers
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center
|