Why Do We Need Constructor With Arguments?

I understand that constructor is used to create instances.
We can have constructors with 0 argument or with one/multiple arguments. Why do we need a contructor with arguments? What is the purpose of doing it?
Thank you for your help.

There are three general ways to provide constructors, like you said:
1) Default constructor (no arguments)
2) One or more constructors with arguments
3) One or more constructors with arguments as well as a default constructor
From a design standpoint, the idea is to give as much information needed for constructing an object up front. Look at the standard Java API for some examples (and because I couldn't find a standard class with just a default constructor, one made up):
public class Foo {
  private long createTime;
  public Foo() {
    createTime = System.currentTimeMillis();
  public String toString() {
    return "This object was created at " + createTime;
}This code has no reason to take any arguments. It does all construction on its own and already has all the information it needs. On the other hand, look at BufferedReader. There's no possible way this object can ever be constructed without an argument. What's it buffering? It doesn't make sense to ever instantiate new BufferedReader(). It'd be useless. So BufferedReader has no default (no-arg) constructor.
Sometimes (very often in Java) you want to do both. Let something be instantiated with no arguments, but also provide the option of creating something with more specific details. A good example is ArrayList, which has three constructors:
public ArrayList() --> Construct an empty ArrayList with the default initial capacity;
public ArrayList(Collection c) --> Construct an ArrayList populated with the contents of another collection;
public ArrayList(int capacity) --> Construct an empty ArrayList with a specific initial capacity.
Sometimes it makes sense just to use the default. Sometimes you want more control over the behavior. Those are the times to use multiple constructors.
Hope this helps!

Similar Messages

  • XML-Encoder --  Constructors with arguments that are not properties

    Hi, I have the problem that I need an argument to initialize the object. That argument isn't stored, to prevent problems with gc (Back-Ref.).
    According to
    http://java.sun.com/products/jfc/tsc/articles/persistence4/
    I have to do something like this:
    Encoder e = new XMLEncoder(System.out);
    e.setPersistenceDelegate(Integer.class,
                             new PersistenceDelegate() {
        protected Expression instantiate(Object oldInstance,
                                          Encoder out) {
            return new Expression(oldInstance,
                                  oldInstance.getClass(),
                                  "new",
                                  new Object[]{ oldInstance.toString() });
    The preceding implementation uses the special method name "new" to refer to the Integer class's string constructor.The problem is that I don't know how to do that, cause I can't receive the needed value from the oldInstance.
    To make it a little bit clearer, I have a structure like this.
    Class A {
    private B b;
    A(){
    b =  new B(this);
    Class B{
    B(final A a){
    }Providing an empty public constructor would be the easiest but ugly solution, cause you offer an constructor which is not intended to be used anywhere, cause it leaves the object in an not valid state. For hibernate I have to provide such an empty constructor anyways, but at least it can be private.
    So is there any other solution out there with limited complexity? You may assume that A will be stored and B is stored by reachability.
    Thanks a lot in advance.
    Greetings Michael
    By the way: the link symbol seems to be broken, whats the plain text markup for that?

    ejp wrote:
    I don't want to, to avoid problems caused by Back-Ref's. They are hard to solve for the GC. No they're not.The Artcicle below tells different. It is in German and unfortunately not freely available.
    Michael K. Klemke, Kersten AuelAbfallwirtschaft
    Wissen, Performance-Optimierung,
    iX 4/2005, Seite 102>
    Also the pages about "Memory Leak Sources" especially "Instances of Inner Classes" are giving an indication, that you should avoid them, at least as long they are having different life cycles.
    http://developers.sun.com/learning/javaoneonline/2007/pdf/TS-2906.pdf
    By the way, if they weren't a problem, why should anyone use WeakReferences?
    But a WeakReference or a SoftReference might be a solution for the above problem. Even I'm not quite sure how XMLEncoder threats them.
    In the meantime I avoid the problem, by providing a standard constructor without any initialization code.
    Introducing a back ref would lead to code like this:
    Class A {
    private B b;
    A(){
    b =  new B(this);
    Class B{
    private A a;
    B(final A a){
    this.a = a;
    }This would be quite hard for the gc to solve, if at least one Instance is still referred form the outside. Even if there isn't an reference form outside, they are only collected if the gc is running longer and can care for such complex structures. Cause the first check if there isn't any active reference is left, won't be true for such constructs. Normally they are only collected just before an OutOfMemoryException.
    I had inherited code form a former college (switched from C++ to Java) which was filled up with this kind of stuff and caused huge memory leaks.
    So you should only use such an construct, if you are quite sure that they are having the same life-cycle and such a peace of code is an exemption and you can't avoid it.
    Greetings Michael

  • How to have constructor with arguments for controller?

    I would like to have the controller have arguments so that they can be a precondition for the object being constructed and not in setters to be added later on. This will reduce errors.
    Unfortunately, fxml only seems to take the no-arg constructor. Is there another way?
    Edited by: likejiujitsu on Apr 20, 2013 10:30 AM

    Here's perhaps a more realistic example. I have a Main.fxml file with a MainController. The event handler for a button in the Main.fxml file is going to load another fxml file (Dialog.fxml) and display the content in a dialog. The controller associated with Dialog.fxml (DialogController) is going to be initialized by passing a String into the constructor; that String value is retrieved from a text field in Main.fxml.
    Main.java:
    package example;
    import java.io.IOException;
    import javafx.application.Application;
    import javafx.fxml.FXMLLoader;
    import javafx.scene.Parent;
    import javafx.scene.Scene;
    import javafx.stage.Stage;
    public class Main extends Application {
      @Override
      public void start(Stage primaryStage) throws IOException {
        Parent root = FXMLLoader.load(getClass().getResource("Main.fxml"));
        primaryStage.setScene(new Scene(root, 400, 200));
        primaryStage.show();
      public static void main(String[] args) {
        launch(args);
    }Main.fxml:
    <?xml version="1.0" encoding="UTF-8"?>
    <?import javafx.scene.layout.VBox?>
    <?import javafx.scene.layout.HBox?>
    <?import javafx.scene.control.Label?>
    <?import javafx.scene.control.TextField?>
    <?import javafx.scene.control.Button?>
    <VBox xmlns:fx="http://javafx.com/fxml" spacing="10"
         fx:controller="example.MainController" fx:id="mainRoot">
         <HBox>
              <Label text="Enter text:" />
              <TextField fx:id="textField" />
         </HBox>
         <Button text="Show Dialog" onAction="#showDialog" />
         <!-- TODO Add Nodes -->
    </VBox>MainController.java:
    package example;
    import java.io.IOException;
    import javafx.fxml.FXML;
    import javafx.fxml.FXMLLoader;
    import javafx.scene.Parent;
    import javafx.scene.Scene;
    import javafx.scene.control.TextField;
    import javafx.stage.Modality;
    import javafx.stage.Stage;
    import javafx.util.Callback;
    public class MainController {
      @FXML
      private TextField textField;
      @FXML
      private Parent mainRoot;
      private final FXMLLoader dialogLoader;
      public MainController() {
        dialogLoader = new FXMLLoader(
            MainController.class.getResource("Dialog.fxml"));
        dialogLoader.setControllerFactory(new Callback<Class<?>, Object>() {
          @Override
          public Object call(Class<?> cls) {
            if (cls == DialogController.class) {
              return new DialogController(textField.getText());
            } else {
              try {
                return cls.newInstance();
              } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
      @FXML
      private void showDialog() throws IOException {
        dialogLoader.setController(null);
        dialogLoader.setRoot(null);
        Parent dialogRoot = (Parent) dialogLoader.load();
        Scene scene = new Scene(dialogRoot, 300, 150);
        Stage dialog = new Stage();
        dialog.initModality(Modality.APPLICATION_MODAL);
        dialog.initOwner(mainRoot.getScene().getWindow());
        dialog.setScene(scene);
        dialog.show();
    }Dialog.fxml
    <?xml version="1.0" encoding="UTF-8"?>
    <?import javafx.scene.layout.VBox?>
    <?import javafx.scene.control.Label?>
    <?import javafx.scene.control.Button?>
    <?import javafx.scene.layout.HBox?>
    <VBox xmlns:fx="http://javafx.com/fxml" fx:controller="example.DialogController"
         fx:id="dialogRoot">
         <Label fx:id="label" />
         <HBox>
              <Button text="Click Me" onAction="#click" />
              <Button text="Close" onAction="#close" />
         </HBox>
    </VBox>DialogController.java
    package example;
    import javafx.fxml.FXML;
    import javafx.scene.Parent;
    import javafx.scene.control.Label;
    public class DialogController {
      private final String text;
      @FXML
      private Label label;
      @FXML
      private Parent dialogRoot;
      public DialogController(String text) {
        this.text = text;
      public void initialize() {
        label.setText(text);
      @FXML
      private void click() {
        System.out.println("Text is " + text);
      @FXML
      private void close() {
        dialogRoot.getScene().getWindow().hide();
    }Edited by: James_D on Apr 22, 2013 8:00 PM

  • Abstract classes: Why do they need constructors?

    As we cannot instantiate an abstract class. Why does an abstract class need a constructor?.can anyone please help me out..Thnq in advance
    OBELISK

    import java.util.*;
    import static java.lang.System.out;
    interface LineItem{
        public int getCost();
    abstract class AbstractLineItem implements LineItem{
      protected String name;
      AbstractLineItem(String name){
         this.name = name;
      public String toString(){
        return this.name+" "+getCost();
      public abstract int getCost();
    class ProductItem extends AbstractLineItem{
       private int quantity, peritem;
       ProductItem(String name, int quantity, int peritem){
         super(quantity+" "+name);
         this.quantity = quantity;
         this.peritem = peritem;
       public int getCost(){
         return this.quantity*this.peritem;
    class FlatFeeItem extends AbstractLineItem{
       private int fee;
       FlatFeeItem(String name, int fee){
         super(name);
         this.fee = fee;
       public int getCost(){
         return this.fee;
    public class Test{
      public static void main(String ... args){
        List<LineItem> items = new ArrayList<LineItem>();
        items.add(new ProductItem("Banana",6,1));
        items.add(new FlatFeeItem("Some boring thing or another",35));
        items.add(new ProductItem("Kiwi",3,3));
        for(LineItem item : items)
          out.println(item);
    }

  • Why do i need vpn with ios 8

    I just downloaded the new ios update and this box keeps popping up saying I need a VPN connection but I don't know what a VPN is

    What type of network are yo trying to connect to?
    A regular home network?
    A business network?
    Just what are yo doing when it pops up?
    What is listed in Settings>General>VPN?

  • Why do I need to connect my Ipad mini with my Mac Book Pro via iCloud?

    Why do I need to connect my Ipad mini with my Mac Book Pro via iCloud? I don't have iCloud on my MacBook Pro and only intend to use the mini to check e-mail and use Garage Band and Photo Booth for song writing when traveling . . .

    Thanks Community! I solved the problem. In fact it was not a problem but lack of understanding. These guys at Apple are way ahead in thir thinking. I will try to explain as short as I can.
    In Lion, ihe Prefferences/Display show only two choices: 6-7 steps of resolution and some color tab. No two screens, no two display to overlap, nothing for us to do. "That was the problem"! Everything is automatic.
    When I connected the HDMI cable to the Miniport into a T-bolt slot, the TV screen showed the "spiral galaxy" how Zyriab is calling it. In fact he gave me the best clue. That shows the connection is good. But where is the Mac Book image?
    You have to drag it to the right out of the Mac Book display area, and "voila!" it will continue on the TV screen. The same with the mouse pointer, push it out ofthe Mac Book display area and you see it on the TV sreen. Good image, you can keep the max resolution, etc. The sound is still on the Book's speakers. I have to figure that out.
    Thank everybody, especialy Zyriab, ne was the closest.
    High regards to everybody

  • Itunes app no longer showing genres or the top charts/genius bar in the top bar ... it only displays a faint music in the centre with just the search box..why? i need them back:-(

    itunes app no longer showing genres or the top charts/genius bar in the top bar ... it only displays a faint music in the centre with just the search box..why? i need them back:-(

    The iTunes Store listing of your podcast is simply reflecting the contents of your podcast feed. Make sure all of the content you want displayed in the iTunes Store is still contained within your feed.
    Are you able to supply your feed for reference?

  • Hi  can any body please tell me how to open the .exe files in mac and why it is not supported with unarchiever app , also i am not able to run and dvd's in my mac its not accepting any cd's or dvd'd why do i need to do some settings for it ?

    Hi  can any body please tell me how to open the .exe files in mac and why it is not supported with unarchiever app , also i am not able to run and dvd's in my mac its not accepting any cd's or dvd'd why? do i need to do some pre defined  settings to run the cd's and dvd's ?

    A .exe file is a Windows executable. OS X does not run Windows programs. If you need to use .exe files then you will need to install Windows on your Mac:
    Windows on Intel Macs
    There are presently several alternatives for running Windows on Intel Macs.
    Install the Apple Boot Camp software.  Purchase Windows XP w/Service Pak2, Vista, or Windows 7.  Follow instructions in the Boot Camp documentation on installation of Boot Camp, creating Driver CD, and installing Windows.  Boot Camp enables you to boot the computer into OS X or Windows.
    Parallels Desktop for Mac and Windows XP, Vista Business, Vista Ultimate, or Windows 7.  Parallels is software virtualization that enables running Windows concurrently with OS X.
    VM Fusionand Windows XP, Vista Business, Vista Ultimate, or Windows 7.  VM Fusion is software virtualization that enables running Windows concurrently with OS X.
    CrossOver which enables running many Windows applications without having to install Windows.  The Windows applications can run concurrently with OS X.
    VirtualBox is a new Open Source freeware virtual machine such as VM Fusion and Parallels that was developed by Solaris.  It is not as fully developed for the Mac as Parallels and VM Fusion.
    Note that Parallels and VM Fusion can also run other operating systems such as Linux, Unix, OS/2, Solaris, etc.  There are performance differences between dual-boot systems and virtualization.  The latter tend to be a little slower (not much) and do not provide the video performance of the dual-boot system. See MacTech.com's Virtualization Benchmarking for comparisons of Boot Camp, Parallels, and VM Fusion. Boot Camp is only available with Leopard or Snow Leopard. Except for Crossover and a couple of similar alternatives like DarWine you must have a valid installer disc for Windows.
    You must also have an internal optical drive for installing Windows. Windows cannot be installed from an external optical drive.

  • How to instantiate classes at run time with constructors having arguments?

    I have to instantiate some classes in the run-time because they are plugins. The name of the plugin (pluginClassName) comes from a configuration file.
    Currently I am doing this to achieve it:-
    UIPlugin plugin = (UIPlugin)Class.forName(pluginClassName).newInstance();However, there is a disadvantage. I can not pass arguments to the constructor of the plugin.
    public class RainyTheme extends UIPlugin {
      public RainyTheme() {
       // bla bla
      public RainyTheme(int x, int y , int width, int height) {
       // set co-ordinates
       // bla bla
      // bla bla bla bla
    }Now if I want to instantiate this plugin at runtime and at the same time I want to pass the 4 arguments as shown in the second constructor, how can I achieve this?

    I have no experience with JME and the limitations of its API, but looking at the API docs ( http://java.sun.com/javame/reference/apis.jsp ) it seems that there are two main versions, CLDC and CDC, of which CLDC is more limited in its API.
    The Class class does not contain the methods getConstructor(Object[]) or getConstructors() in this version ( http://java.sun.com/javame/reference/apis/jsr139/java/lang/Class.html ), so it seems that if you are using CLDC then there is no way to reflectively call a constructor with parameters. You'd have to find another way to do what you want, such as use the noarg constructor then initialise the instance after construction.

  • Why do you need to shift click to select stroke color with eyedropper tool?

    Hi,
    Quick question..
    Why do you need to shift click to select the stroke color with the eyedropper tool?
    I had the problem where I could not do this earlier and found the solution on this forum.
    However I still do not understand the reason for this.
    Appreciate if anyone could explain it to me.
    Thanks in advance.
    Nori

    Hi, Nori,
    If you have the red and blue rectangle selected and the Fill square selected in the tool panel, as at bottom left, then hold the shift key down and click with the eyedropper on the green stroke in the upper rectangle, then the red fill will turn green but the stroke stays blue. If you select Stroke, as at bottom right, then shift-click with the eyedropper on the green stroke, the blue stroke will turn green but the fill stays red. With Fill selected and shift-click on the yellow fill, the red fill turns yellow; with Stroke selected the blue stroke turns yellow. If you do not depress the shift key, the red and blue rectangle will become yellow and green.
    It's complicated to explain, but I think that if you try it step by step it will make sense to you.
    Peter

  • Object with argument constructor in ATG

    HI guys
    Is it possible to craete an object with argument constructor with component in atg
    if it is possible give me an example

    With ATG 10.0.3 and later, you can use an $instanceFactory to create objects with constructor objects or create a Nucleus component from factory (either a static class method, or a method of another Nucleus component).
    Documentation (and an example) are here: http://docs.oracle.com/cd/E36434_01/Platform.10-1-2/ATGPlatformProgGuide/html/s0208parameterconstructorinstancefact01.html

  • Hi All, Is it possible to invoke dynamically, constructor with an argument?

    Hi All, Is it possible to invoke dynamically, constructor with an argument
    Thanks in advance

    Strongly depends on what's dynamic.

  • Why do I need J2SE if I can do everything with J2RE?

    Hi,
    I'm writing Java (with eclipse) for some time now, but I still don't understand why do I need to download J2SE ?
    It seems that I can write code & run it with J2RE only... so what is the benefit of J2SE?
    Thanks for your help...

    Eclipse has a compiler in it, presumably. Or possibly it delegates to javac and you just haven't found it.
    You don't need to have an external command-line compiler if you only want to compile code with Eclipse, although it certainly can be helpful to have a duplicate tool with a different interface sometimes.
    Also the JDK (that is, the Java SDK, as opposed to the libraries; sometimes the terms are used interchangably) comes with other useful tools, like javap and jar.

  • Why do i need ios8 to use find my iphone with 5c

    why do i need ios8 to use find my iphone with 5c

    Yes. If the device doesn't have a connection to the Internet, then there is no way for it to report its position.

  • Ok so my i need help with my iphone 4s... i have about $5.00 of credits left of the itunes card i got and i decided to get a show and it says i need to verify my credit card, why doesnt it just use the credits i have? its under 5 bucks? help me please

    ok so my i need help with my iphone 4s... i have about $5.00 of credits left of the itunes card i got and i decided to get a show and it says i need to verify my credit card, why doesnt it just use the credits i have? its under 5 bucks? help me please

    You have to do it here for help
    iTunes Store Support
    http://www.apple.com/emea/support/itunes/contact.html

Maybe you are looking for

  • Safari and Google Video Chat

    Ever since I updated my Flash I can not get Video when trying to use Google Video Chat using Safari, it works using Crome. Does anyone know how to fix it in Safari?

  • Play & Pause buttons work...but not with each other

    V!P and dzedwards were a big help to me yesterday but now I've come up against something else... I've got 3 music buttons on a page. The code that I have plays and pauses each button perfectly. But if I have Button 1 playing and I click on button 2 (

  • Sap error when displaying dynpro

    Hi guys, i need to display a dynpro with some data, the problem is that sometimes i got an abap error when i call the dynpro. the error is because when u try tu put a currency with the negative symbol ( - ), i create the field as currency with refere

  • Swap payload to attachment

    Hi experts, is there any way to swap payload to attachment except deploying a custom module in a receive SOAP adapter? Regards,

  • Getting rid of ? from the dock after upgrading to ML

    After upgrading to Mountain Lion the old ichat, ical and address book icons are now "?" and I can't get them off the dock.  Dragging them off doesn't work, dragging to the trash doesn't work, and right clicking on it doesn't work.  Any ideas?