This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Java in General and the fly likes Overriding Constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "Overriding Constructor" Watch "Overriding Constructor" New topic
Author

Overriding Constructor

little master
Greenhorn

Joined: Jan 30, 2009
Posts: 3
Hi All,

I am new to Java, can we override a constructor..? and what are the uses of overriding it. is it is a good practice of doing it.

Please help me this was a question asked in interview.
Thanks in adv.

Regards
LM.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

No you cannot override a constructor. You can overload it, but non-static non-final methods are the only members that can be overridden.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
little master
Greenhorn

Joined: Jan 30, 2009
Posts: 3
public class OverRide {
public OverRide(){
System.out.println("from constructor");
}

}


public class OverRidden extends OverRide {

public void OverRide(){
System.out.println("from OveRidden");
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
OverRidden or = new OverRidden();
or.OverRide();

}

public void myJob() {
// TODO Auto-generated method stub

}

}

OUTPUT:
from constructor
from OveRidden

i have the above code can you please look into it.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

1) read your private messages and follow the instructions inside.
2) UseCodeTags
3) that's constructor chaining. That's something completely different from overriding.
Darryl Burke
Bartender

Joined: May 03, 2008
Posts: 4571
    
    5

edit Cross posted
http://forums.sun.com/thread.jspa?threadID=5437288


luck, db
There are no new questions, but there may be new answers.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Hi,

Welcome to JavaRanch!

First, a bit of business: you may not have read our naming policy on the way in. It requires that you use a full, real (sounding) first and last name for your display name. Initials aren't enough. You can change your display name here. Thanks!

Now, as to your question: what you have is a method returning void with the same name as a class. That's not a constructor -- constructors don't have a return type, and you also can't call them directly. You can only call them using "new" or "super". In your OverRide class, that is a constructor.


[Jess in Action][AskingGoodQuestions]
 
GeeCON Prague 2014
 
subject: Overriding Constructor