Classes and Constructor

If i have to build a class with a constructor that prompts user to input X integers and store them into the array registers how do I do it? Couple specific questions:
1. What part of program contains the instructions for user to input data?Is it in the control program or in the object?
2. If I do the array in the object does the array int[] myarray = new int[10]have to be before constructor definition?
3. Does the scanner belong in the object or in the control program?
I appreciate any info provided. I do not expect this assignment to be done for me, just looking to be educated.

Sarugaki wrote:
If i have to build a class with a constructor that prompts user to input X integers and store them into the array registers how do I do it?Personally, I think that's sloppy design. Constructors shouldn't ask for user input, IMHO. A constructor should end with an object in a valid state, and that's difficult to do when you're dependent on the user inputting meaningful information. It also creates a (partial) dependency on a particular usage pattern. You can mitigate this by throwing an exception, but still.
Couple specific questions:
1. What part of program contains the instructions for user to input data?Is it in the control program or in the object?Eh? There are library classes that can query user input. You can write a class to call those classes. If you call them in the constructor, then then object has the code (well, the class does). I'm not sure I understand your question.
2. If I do the array in the object does the array int[] myarray = new int[10]have to be before constructor definition?If you put that line inside of the constructor, then myarray will be a local variable that goes away when the constructor is finished. You probably mean for it to be a field of the class (thus, declared outside of the constructor).
3. Does the scanner belong in the object or in the control program?By "control program" I presume you mean the class with the main() method.
Personally, I think it makes more sense to do I/O outside of the constructor, and so, I'd put it in the main() method (or some other method).
Another option might be, for example, to create a static method in the class whose objects you are creating. This static method would create a Scanner, get user input, and then use that input (if it's valid) to create an object. If the input is invalid, it would return null. In this case, the Scanner would go in the class of the the object in question, and not in that thing which you're calling the "control program".
"You have been selected to play on the game grid." Extra points to whomever can spot that reference (and why I mentioned it).
ah, too slow again
Edited by: paulcw on Apr 27, 2008 3:04 PM

Similar Messages

  • Using Class and Constructor to create instances on the fly

    hi,
    i want to be able to create instances of classes as specified by the user of my application. i hold the class names as String objects in a LinkedList, check to see if the named class exists and then try and create an instance of it as follows.
    the problem im having is that the classes i want to create are held in a directory lower down the directory hierarchy than where the i called this code from.
    ie. the classes are held in "eccs/model/behaviours" but the VM looks for them in the eccs directory.
    i cannot move the desired classes to this folder for other reasons and if i try to give the Path name to Class.forName() it will not find them. instead i think it looks for a class called "eccs/model/behaviours/x" in the eccs dir and not navigate to the eccs/model/behaviours dir for the class x.
    any ideas please? heres my code for ye to look at in case im not making any sense:)
    //iterator is the Iterator of the LinkedList that holds all the names of the
    //classes we want to create.
    //while there is another element in the list.
    while(iterator.hasNext())
    //get the name of the class to create from the list.
    String className = (String) iterator.next();
    //check to see if the file exists.
    if(!doesFileExist(className))
    System.out.println("File cannot be found!");
    //breake the loop and move onto the next element in the list.
    continue;
    //create an empty class.
    Class dynamicClass = Class.forName(className);
    //get the default constructor of the class.
    Constructor constructor = dynamicClass.getConstructor(new Class[] {});
    //create an instance of the desired class.
    Behaviour beh = (Behaviour) constructor.newInstance(new Object[] {});
    private boolean doesFileExist(String fileName)
    //append .class to the file name.
    fileName += ".class";
    //get the file.
    File file = new File(fileName);
    //check if it exists.
    if(file.exists())
    return true;
    else
    return false;
    }

    ok ive changed it now to "eccs.model.behaviours" and it seems to work:) many thanks!!!
    by the following you mean that instead of using the method "doesFileExist(fileName)" i just catch the exception and throw it to something like the System.out.println() ?
    Why don't you simply try to call Class.forName() and catch the exception if it doesn't exist? Because as soon as you package up your class files in a jar file (which you should) your approach won't work at all.i dont think il be creating a JAR file as i want the user to be able to create his/her own classes and add them to the directory to be used in the application. is this the correct way to do this??
    again many thanks for ye're help:)

  • Abstract classes and constructors - cannot call abs. methods in CONSTRUCTOR

    Let me explain the scenario:
    I'm building a program in which I need to read a file (among other things) and I intend to use object orientation to it's fullest in doing so. I thought of creating an abstract FILE class which has the commonalities, and two subclasses SERVER_FILE and PC_FILE, which implement the abstract method GET_CONTENTS in different ways (OPEN DATASET / GUI_UPLOAD), same for the CHOOSE method which allows to select the file from it's corresponding source.
    Initially I've used an interface but since another tasks like setting the file path are common for both, switched to an ABSTRACT class.
    Now, the problem is, from the main code I intend to use a FILE reference to handle either type of file. At the instantiation moment I'd like the path attribute to be set; if it was not set by parameter, i'd like to call the CHOOSE method which is abstract for the superclass. Since this is common for either subclass, I need a way to code it once in the superclass. But I get an error because the CHOOSE method is abstract.
    This is the problem code (extracts):
    *       CLASS lcl_file DEFINITION
    CLASS lcl_file DEFINITION ABSTRACT.
      PUBLIC SECTION.
        METHODS:
          constructor
            IMPORTING
              i_path  TYPE string OPTIONAL
            EXCEPTIONS
              no_path_chosen,
          get_contents ABSTRACT
            RETURNING
              value(rt_contents) TYPE string_table
            EXCEPTIONS
              read_error.
      PROTECTED SECTION.
        DATA:
          _v_path        TYPE string.
        METHODS:
          choose ABSTRACT
            EXCEPTIONS
              no_path_chosen,
          set_path
            IMPORTING
              i_path  TYPE string.
    ENDCLASS.                    "lcl_file DEFINITION
    *       CLASS lcl_file IMPLEMENTATION
    CLASS lcl_file IMPLEMENTATION.
      METHOD constructor.
        IF i_path IS SUPPLIED.
          CALL METHOD set_path
            EXPORTING
              i_path = i_path.
        ELSE.
    *---->>>> PROBLEM CALL - CAN'T BE DONE!!
          CALL METHOD choose
            EXCEPTIONS
              no_path_chosen = 1.
          IF sy-subrc = 1.
            RAISE no_path_chosen.
          ENDIF.
        ENDIF.
      ENDMETHOD.                    "constructor
      METHOD set_path.
        _v_path = i_path.
      ENDMETHOD.                    "set_path
    ENDCLASS.                    "lcl_file IMPLEMENTATION
    *       CLASS lcl_server_file DEFINITION
    CLASS lcl_server_file DEFINITION
                          INHERITING FROM lcl_file.
      PUBLIC SECTION.
        METHODS:
          get_contents REDEFINITION.
      PROTECTED SECTION.
        METHODS:
          choose       REDEFINITION.
    ENDCLASS.                    "lcl_server_file  DEFINITIO
    *       CLASS lcl_server_file IMPLEMENTATION
    CLASS lcl_server_file IMPLEMENTATION.
      METHOD choose.
        DATA:
          l_i_path     TYPE dxfields-longpath,
          l_o_path     TYPE dxfields-longpath.
        CALL FUNCTION 'F4_DXFILENAME_TOPRECURSION'
          EXPORTING
            i_location_flag = 'A'  " Application server
            i_path          = l_i_path
            fileoperation   = 'R'  " Lectura
          IMPORTING
            o_path          = l_o_path
          EXCEPTIONS
            rfc_error       = 1
            OTHERS          = 2.
        IF sy-subrc = 0 AND l_o_path <> l_i_path.
          MOVE l_o_path TO _v_path.
        ELSE.
          RAISE no_path_chosen.
        ENDIF.
      ENDMETHOD.                    "choose
      METHOD get_contents.
        DATA: l_line   LIKE LINE OF rt_contents,
              l_osmsg  TYPE string.
        CHECK NOT _v_path IS INITIAL.
        OPEN DATASET _v_path FOR INPUT
                                 IN TEXT MODE
                                 MESSAGE l_osmsg.
        IF sy-subrc <> 0.
          MESSAGE e000(oo) WITH l_osmsg
                           RAISING read_error.
        ELSE.
          DO.
            READ DATASET _v_path INTO l_line.
            IF sy-subrc = 0.
              APPEND l_line TO rt_contents.
            ELSE.
              EXIT.
            ENDIF.
          ENDDO.
          CLOSE DATASET _v_path.
        ENDIF.
      ENDMETHOD.                    "get_contents
    ENDCLASS.                    "lcl_server_file IMPLEMENTATION
    *       CLASS lcl_pc_file DEFINITION
    CLASS lcl_pc_file  DEFINITION
                       INHERITING FROM lcl_file.
      PUBLIC SECTION.
        METHODS:
          get_contents REDEFINITION.
      PROTECTED SECTION.
        METHODS:
          choose       REDEFINITION.
    ENDCLASS.                    "lcl_pc_file  DEFINITIO
    *       CLASS lcl_pc_file IMPLEMENTATION
    CLASS lcl_pc_file IMPLEMENTATION.
      METHOD choose.
        DATA:
          l_i_path     TYPE dxfields-longpath VALUE 'C:\',
          l_o_path     TYPE dxfields-longpath.
        CALL FUNCTION 'F4_DXFILENAME_TOPRECURSION'
          EXPORTING
            i_location_flag = 'P'  " PC
            i_path          = l_i_path
            fileoperation   = 'R'  " Lectura
          IMPORTING
            o_path          = l_o_path
          EXCEPTIONS
            rfc_error       = 1
            OTHERS          = 2.
        IF sy-subrc = 0 AND l_o_path <> l_i_path.
          MOVE l_o_path TO _v_path.
        ELSE.
          RAISE no_path_chosen.
        ENDIF.
      ENDMETHOD.                    "choose
      METHOD get_contents.
        CHECK NOT _v_path IS INITIAL.
        CALL METHOD cl_gui_frontend_services=>gui_upload
          EXPORTING
            filename                = _v_path
          CHANGING
            data_tab                = rt_contents
          EXCEPTIONS
            file_open_error         = 1
            file_read_error         = 2
            no_batch                = 3
            gui_refuse_filetransfer = 4
            invalid_type            = 5
            no_authority            = 6
            unknown_error           = 7
            bad_data_format         = 8
            header_not_allowed      = 9
            separator_not_allowed   = 10
            header_too_long         = 11
            unknown_dp_error        = 12
            access_denied           = 13
            dp_out_of_memory        = 14
            disk_full               = 15
            dp_timeout              = 16
            OTHERS                  = 17.
        IF sy-subrc <> 0.
          RAISE read_error.
        ENDIF.
      ENDMETHOD.                    "get_contents
    ENDCLASS.                    "lcl_pc_file IMPLEMENTATION
    * Data
    DATA: gr_file          TYPE REF TO lcl_file.
    * Main Program
    START-OF-SELECTION.
    *   Get text lines from file
        IF p_srv = abap_true.
          CREATE OBJECT gr_file
            TYPE
              lcl_server_file
            EXCEPTIONS
              no_path_chosen  = 1.
        ELSE.
          CREATE OBJECT gr_file
            TYPE
              lcl_pc_file
            EXCEPTIONS
              no_path_chosen = 1.
        ENDIF.
    On a 4.6c system this code gave me a dump, while on my NW7.0 SP it doesn't even activate with the following error:
    You cannot call abstract methods in the "CONSTRUCTOR" method.
    - Following some suggestions from Java forums i've tried to define the constructor in the base class as PROTECTED or PRIVATE instead, then calling super->constructor from the subclasses, but I get this error in german:
    Sichtbarkeit des Konstruktors darf nicht spezieller als die Sichtbarkeit der Instanzerzeugung (CREATE-Zuzatz) sein.
    which Altavista translates like:
    Visibility of the constructor may not be more special than the
    visibility of the instance production (CREATE Zuzatz).
    - I've also thought of defining the CHOOSE method as a class (not instance) one, then calling it before creating the file object which maybe solves the problem, but I see that approach more "procedural oriented" which i'm trying to avoid.
    - Of course I could define a constructor for each subclass, but both would have exactly the same code.
    I'm really lost on how should I code this. My main focus is on avoiding code dupplication.
    I hope someone with more OO experience can see what I'm trying to do and sheds some light.
    Many thanks for reading all this!

    Dear Alejandro,
        When i saw your code, you are trying to access an astract method CHOOSE(which is actually implemented in sub class) from the constructor of the base class which is not possible.  By this time, we don't know which sub class it is refering to, so it gives an error.   I see two solutions for this..
    1.  To define constructor in sub class and call the choose method from the consturctor of the sub class(which in this case is reputation of the same again for each sub class)
    2.  Remove the calling of choose method from the constructor of the main class and call it separately(after creating the object).   By now we know which sub class we are refering to.   I would have designed the program in the following way.
    *       CLASS lcl_file DEFINITION
    CLASS lcl_file DEFINITION ABSTRACT.
      PUBLIC SECTION.
        METHODS:
          constructor
            IMPORTING
              i_path  TYPE string OPTIONAL
            EXCEPTIONS
              no_path_chosen,
          get_contents ABSTRACT
            RETURNING
              value(rt_contents) TYPE string_table
            EXCEPTIONS
              read_errorm,
          set_path ABSTRACT
            EXCEPTIONS
              no_path_chosen.
      PROTECTED SECTION.
        DATA:
          _v_path        TYPE string.
    *    METHODS:
    *      choose ABSTRACT
    *        EXCEPTIONS
    *          no_path_chosen,
    *      set_path ABSTRACT
    *        IMPORTING
    *          i_path  TYPE string.
    ENDCLASS.                    "lcl_file DEFINITION
    *       CLASS lcl_file IMPLEMENTATION
    CLASS lcl_file IMPLEMENTATION.
      METHOD constructor.
        IF i_path IS SUPPLIED.
          _v_path = i_path.
    *      CALL METHOD set_path
    *        EXPORTING
    *          i_path = i_path.
    *    ELSE.
    **---->>>> PROBLEM CALL - CAN'T BE DONE!!
    *      CALL METHOD choose
    *        EXCEPTIONS
    *          no_path_chosen = 1.
    *      IF sy-subrc = 1.
    *        RAISE no_path_chosen.
    *      ENDIF.
        ENDIF.
      ENDMETHOD.                    "constructor
    * METHOD set_path.
    *    _v_path = i_path.
    * ENDMETHOD.                    "set_path
    ENDCLASS.                    "lcl_file IMPLEMENTATION
    *       CLASS lcl_server_file DEFINITION
    CLASS lcl_server_file DEFINITION
                          INHERITING FROM lcl_file.
      PUBLIC SECTION.
        METHODS:
          get_contents REDEFINITION,
          set_path     REDEFINITION.
    *  PROTECTED SECTION.
    *    METHODS:
    *      choose       REDEFINITION.
    ENDCLASS.                    "lcl_server_file  DEFINITIO
    *       CLASS lcl_server_file IMPLEMENTATION
    CLASS lcl_server_file IMPLEMENTATION.
      METHOD set_path.
        DATA:
          l_i_path     TYPE dxfields-longpath,
          l_o_path     TYPE dxfields-longpath.
        CHECK _v_path IS INITIAL.
        CALL FUNCTION 'F4_DXFILENAME_TOPRECURSION'
          EXPORTING
            i_location_flag = 'A'  " Application server
            i_path          = l_i_path
            fileoperation   = 'R'  " Lectura
          IMPORTING
            o_path          = l_o_path
          EXCEPTIONS
            rfc_error       = 1
            OTHERS          = 2.
        IF sy-subrc = 0 AND l_o_path  = l_i_path.
          MOVE l_o_path TO _v_path.
        ELSE.
          RAISE no_path_chosen.
        ENDIF.
      ENDMETHOD.                    "set_path
      METHOD get_contents.
        DATA: l_line   LIKE LINE OF rt_contents,
              l_osmsg  TYPE string.
        CHECK NOT _v_path IS INITIAL.
    *    OPEN DATASET _v_path FOR INPUT
    *                             IN TEXT MODE
    *                             MESSAGE l_osmsg.
        IF sy-subrc  = 0.
    *      MESSAGE e000(oo) WITH l_osmsg
    *                       RAISING read_error.
        ELSE.
          DO.
            READ DATASET _v_path INTO l_line.
            IF sy-subrc = 0.
              APPEND l_line TO rt_contents.
            ELSE.
              EXIT.
            ENDIF.
          ENDDO.
          CLOSE DATASET _v_path.
        ENDIF.
      ENDMETHOD.                    "get_contents
    ENDCLASS.                    "lcl_server_file IMPLEMENTATION
    *       CLASS lcl_pc_file DEFINITION
    CLASS lcl_pc_file  DEFINITION
                       INHERITING FROM lcl_file.
      PUBLIC SECTION.
        METHODS:
          get_contents REDEFINITION,
          set_path     REDEFINITION.
    *  PROTECTED SECTION.
    *    METHODS:
    *      choose       REDEFINITION.
    ENDCLASS.                    "lcl_pc_file  DEFINITIO
    *       CLASS lcl_pc_file IMPLEMENTATION
    CLASS lcl_pc_file IMPLEMENTATION.
      METHOD set_path.
        DATA:
          l_i_path     TYPE dxfields-longpath VALUE 'C:\',
          l_o_path     TYPE dxfields-longpath.
        CHECK _v_path IS INITIAL.
        CALL FUNCTION 'F4_DXFILENAME_TOPRECURSION'
          EXPORTING
            i_location_flag = 'P'  " PC
            i_path          = l_i_path
            fileoperation   = 'R'  " Lectura
          IMPORTING
            o_path          = l_o_path
          EXCEPTIONS
            rfc_error       = 1
            OTHERS          = 2.
        IF sy-subrc = 0 AND l_o_path  = l_i_path.
          MOVE l_o_path TO _v_path.
        ELSE.
          RAISE no_path_chosen.
        ENDIF.
      ENDMETHOD.                    "set_path
      METHOD get_contents.
        CHECK NOT _v_path IS INITIAL.
        CALL METHOD cl_gui_frontend_services=>gui_upload
          EXPORTING
            filename                = _v_path
          CHANGING
            data_tab                = rt_contents
          EXCEPTIONS
            file_open_error         = 1
            file_read_error         = 2
            no_batch                = 3
            gui_refuse_filetransfer = 4
            invalid_type            = 5
            no_authority            = 6
            unknown_error           = 7
            bad_data_format         = 8
            header_not_allowed      = 9
            separator_not_allowed   = 10
            header_too_long         = 11
            unknown_dp_error        = 12
            access_denied           = 13
            dp_out_of_memory        = 14
            disk_full               = 15
            dp_timeout              = 16
            OTHERS                  = 17.
        IF sy-subrc  = 0.
    *      RAISE read_error.
        ENDIF.
      ENDMETHOD.                    "get_contents
    ENDCLASS.                    "lcl_pc_file IMPLEMENTATION
    * Data
    DATA: gr_file          TYPE REF TO lcl_file.
    * Main Program
    START-OF-SELECTION.
    *   Get text lines from file
      IF abap_true = abap_true.
        CREATE OBJECT gr_file
          TYPE
            lcl_server_file
          EXCEPTIONS
            no_path_chosen  = 1.
      ELSE.
        CREATE OBJECT gr_file
          TYPE
            lcl_pc_file
          EXCEPTIONS
            no_path_chosen = 1.
      ENDIF.
      gr_file->set_path( ).
    Regards
    Kesava
    Edited by: Kesava Chandra Rao on Mar 19, 2008 11:44 AM

  • Assistance Class and Constructor

    Hi,
    I've created an assistance class + a constructor for it. This constructor needs a parameter to initialize the Assistance Class.
    However I'm unable to pass it on since the instantiation of WD_ASSIST is done by the framework.
    How can I achieve this?
    Thanks

    Yes Thomas. I totally agree with you. ideally an assistance class is always instantiated by the WD framework. But I just talked about the technical possibility of having a constructor for an assistance class.
    Apart from the embedded component usage one more possibility which comes to my mind is coverting a normal class ( being used elese where in normal report programs where constructor is necessary for instantiating parameters) into an assistance class. Although the class may be copied into a new class and then by deleting the constructor and creating a method for the purpose which constructor used to do.
    I welcome your thoughts on this scenario.

  • Abstract classes and Constructors

    I am wiondering how can an Abstract class have a constructor?
    Won't the constructor of the derived class
    automatically invoke the constructor of Shape
    by calling super()implicitly
    That means that an object of type Shape has been created
    Or have I overlooked a certain point?
    abstract class Shape {
         public String color;
         public Shape() {
         public void setColor(String c) {
              color = c;
         public String getColor() {
              return color;
         abstract public double area();
    public class Point extends Shape {
         static int x, y;
            // ?? Wont this constructor invoke the super class's constructor?
         public Point() {
              x = 0;
              y = 0;
         public double area() {
              return 0;
         public static void print() {
              System.out.println("point: " + x + "," + y);
         public static void main(String args[]) {
              Point p = new Point();
              p.print();
    }

    bhuru_luthria wrote:
    I am wiondering how can an Abstract class have a constructor?
    Won't the constructor of the derived class
    automatically invoke the constructor of Shape
    by calling super()implicitly If you don't explicitly invoke a superclass c'tor, super() will be called, but you can also explicitly invoke any non-private parent constructor from the child's constructor.
    That means that an object of type Shape has been createdC'tors don't create objects. They initialize newly created objects to valid state.

  • Best practice for class and constructors

    I'm writing a small utility class that has a private member that is a List. I'm troubled when I think about where this List should be created - in the declaration of the reference or in the default constructor - thus having all other constructors call the default.
    Should I have:
    public Class Foo() {
        private List myList = new ArrayList();
      public Foo() {
      public Foo(String myFoo) {
      public Foo(String[] myFoo) {
      // more methods....
    }or would it be better to code it as:
    public Class Foo() {
        private List myList;
      public Foo() {
        myList = new ArrayList();
      public Foo(String myFoo) {
        foo();
       // other stuff
      public Foo(String[] myFoo) {
        foo();
       // other stuff
      // more methods....
    }In the first option, I know from putting a watch on myList that it stays undefined until any one of the constructors in called. This would seem to me to be the best approach as it doesn't require future additional constructors to have to be written to specifically call the default constructor just to get the ArrayList created. What's typically done in this situation? Which one is considered "good form" or is there a better way?

    I'm writing a small utility class that has a private
    member that is a List. I'm troubled when I think
    about where this List should be created - in the
    declaration of the reference or in the default
    constructor - thus having all other constructors call
    the default.It's not done this way - you have to call this().
    I think the better solution is to have the creation and initialization of the List in the most specific constructor, and have the default call that:
    public class Foo
        private List myList;
        public Foo()
            this(Collections.EMPTY_LIST);
        public Foo(List newList)
            this.myList = new ArrayList(newList);
    }%

  • Model classes and constructors for relationships

    Can someone help me understand what purpose the Department constructor has in the class below, taken from https://msdn.microsoft.com/en-us/data/jj591617.aspx
    public class Department
    public Department()
    this.Courses = new HashSet<Course>();
    // Primary key
    public int DepartmentID { get; set; }
    public string Name { get; set; }
    public decimal Budget { get; set; }
    public System.DateTime StartDate { get; set; }
    public int? Administrator { get; set; }
    // Navigation property
    public virtual ICollection<Course> Courses { get; private set; }
    Versus this example where they don't use a constructor, taken from http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-a-more-complex-data-model-for-an-asp-net-mvc-application
    public class Department
    public int DepartmentID { get; set; }
    [StringLength(50, MinimumLength=3)]
    public string Name { get; set; }
    [DataType(DataType.Currency)]
    [Column(TypeName = "money")]
    public decimal Budget { get; set; }
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    [Display(Name = "Start Date")]
    public DateTime StartDate { get; set; }
    public int? InstructorID { get; set; }
    public virtual Instructor Administrator { get; set; }
    public virtual ICollection<Course> Courses { get; set; }
    The Course class is identical in both.
    Is this just a case of the latter being EF6 and the former deprecated?
    Thanks
    You are so wise...like a miniature budha covered in fur. -Anchorman

    public class
    Department
        public Department()
            this.Courses
    = new
    HashSet<Course>();
    What is happening is that when Department class is instantiated into an object,  Courses gets
    instantiated into a object too within Department.
    var dept = new Department();
    It means that Courses can be addressed/accessed immediately within Department, because it got instantiated when Department was instantiated.
    dept.Courses.Add(Course);
    Without Courses object being instantiated  within Department's constructor, then you would have to instantiate the Courses object outside of the Department object before you could address/access the Courses
    object within the Department object.
    var dept = new Department();
    dept.Courses = new HashSet<Course>();
    The second class example you show assumes that Courses was instantiated at some point to be an object in the Department object in code outside of the Department class.
    The first class example has Courses instantiated as an object within Department and ready to go when Department object is instantiated, and the second example is you had better at some point in code outside of the Department object instantiate Courses as
    an object within the Department object, because otherwise, it's object not set to an instance of an object error when you try to address Department.Courses.  

  • Classes, and constructors and instance variables . . . oh my!

    wow, I am really struggling with the stuff we are doing in class for the last few days. I am going to post our assignment and point out specific things I don't understand. I don't understand some of the syntax and the overall logical flow of how parameters get passed back and forth, etc. I have been over our book and class examples and I am still confused.
    Here is one part of the assignment:
    "Create two instances of the MyDate class named begDate and endDate, by using the MyDate constructor after having prompted the user
    3 times for each date for values of a valid month, day, and year."
    Q: how do I create two instances using the constructor?
    (from our assignment) "Within the MyDate class:
         Include three private int variables, named month, day, and year.
         Include a constructor that sets (sets them to what?!) the values of month, day, and year."
    here is what I have:
    public class MyDate {
         private int month, day, year;
         public MyDate (int month, int day, int year){
              month = 0;
              day = 0;
              year = 0;
         }//MyDate Constructor(from our assignment) "Create two instances of the MyDate class named begDate and endDate, by using the MyDate constructor after having prompted the user 3 times for each date for values of a valid month, day, and year."
    and here is what I have in the executable class (it isn't much because I already have an error; it says I can't convert String to MyDate):
    public static void main(String[] args) {
              MyDate begDate = JOptionPane.showInputDialog("beg. month?");
         }I guess I don't know how to use the constructor correctly. Sorry, but I have tried to make this as clear as possible.

    I will give you a start:
    public static void main(String[] args) {
              MyDate begDate new MyDate(JOptionPane.showInputDialog("beg. month?"), JOptionPane.showInputDialog("beg. day?"), JOptionPane.showInputDialog("beg. year?"));
    public class MyDate {
         private int month, day, year;
         public MyDate (int month, int day, int year){
              this.month = month;
              this.day = day;
              this.year = year;
         }//MyDate Constructor
    /code]
    Haven't tested it, maybe made some type mismatches, but at leasy try this one                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Abstract Class and Constructors

    Why is it that Constructors are permitted within an abstract class?

    But how is it possible to create/instantiate Abstract
    classes?It's not. The only class that gets instantiated is the concrete child class.
    As somebody already said, invoking a constructor does NOT create the object.
    When you do new Foo(), the constructor does NOT instantiate the Foo. The new operator does. It allocates the memory, sets default values for member variables, and then it invokes the constructor. If that ctor invokes a chain of other ctors in itself and its parent, and so on up the chain, you're NOT creating more and more objects. You're just running additional constructors on the one object that has already been created.
    What is the use of a constructor in an abstract class?Just like in any other class: to initialize fields.

  • Help with first approach to Class and Constructor

    Hello guys
    I have a homework but I'm totally lost.
    Here is the assignment:
    **Write the fields, the constructor and the methods of the class below.**
    **public class HourlyEmployee**
    **The class has 4 private fields:**
    **private String name; // the name**
    **private String position; // the position in the company**
    **private double rate; // the hourly rate**
    **private double hours = 0.0; // the hours that the employee worked**
    **The constructor has the header**
    **public HourlyEmployee( String n, Spring pos, double pay)**
    **that puts n into name, pos into position, and pay into rate.**
    **The class has the methods below.**
    **public String getName()**
    **public String getPosition()**
    **public double getRate()**
    **public double getHours()**
    **public void setName(String newName)**
    **public void getARaise(double inc)**
    **public void work(double time)**
    **public double getPaid()**
    **public boolean equals(HourlyEmployee other)**
    **public String toString()**
    **The first 4 methods return the name, the position, the rate**
    **and the hours, in this order.**
    **The method getARaise adds inc to rate.**
    **The method work adds time to hours.**
    **The program getPaid computes and returns the weekly pay.**
    **The worker gets paid one time and a half for overtime (over**
    **40 hours of work). Don't forget to reset hours to 0 before**
    **you leave this method.**
    **The method**
    **public boolean equals(HourlyEmployee other)**
    **returns true if this is equals to other and false**
    **if they are not. Two hourly employees are equal**
    **if they have the same name, the same position and**
    **the same rate.**
    **The last method returns the string**
    **HourlyEmployee[name = ...][position = ....][rate = ...]**
    **where ... stands for the name, position, and the rate**
    **of the employee.**
    Here is what I have so far:
    public class HourlyEmployee
    *// the fields*
    private String name; // the name
    private String position; // the position in the company
    private double rate; // the hourly rate
    private double hours = 0.0; // the hours that the employee worked
    *// This constructor sets the name, position and rate*
    */ @param n is the name*
    *@param pos is the position*
    *@param pay is the rate*
    public HourlyEmployee( String n, String pos, double pay)
    name = n;
    position = pos;
    rate = pay;
    *//get a new name*
    *//@param newName is the new name to be entered*
    public void setName (String newName)
    <
    +//get a raise+
    +//@param inc is the amount to be increased+
    public void getARaise (double inc)*
    *+{+*
    rate = inc;*
    System.out.println ("The rate is " rate);*
    +}+
    +//get the time worked+
    +//@param time is the amount of hours worked+
    public void work (double time)*
    *+{+*
    hours = time;*
    System.out.println ("The amount of hour is " hours);*
    +}+
    +//get the amount paid+
    +//@param rate is the amount of money+
    public void getPaid ()*
    *+{+*
    rate = hours;*
    if ( hours > 40 )*
    rate = 1.5; *
    System.out.println ("The amount paid is " rate);*
    *//compare employees*
    *//@param rate*
    public boolean equals (HourlyEmployee other)
    return rate == other.rate
    *&& name.equals (other.name);*
    But I don't really understand what's going on.
    What is the difference between setName and getName?
    Didn't the constructor set the name, the position and the rate already?
    I don't know where I'm standing or where I'm going.
    Any help?
    Thank you

    Ok, this is what I have so far:
    public class HourlyEmployee
             // the fields
            private String name; // the name
            private String position; // the position in the company
            private double rate; // the hourly rate
            private double hours = 0.0; // the hours that the employee worked
            // This constructor sets the name, position and rate
            /* @param n is the name
             * @param pos is the position
             * @param pay is the rate
            public HourlyEmployee( String n, String pos, double pay)
              name = n;
              position = pos;
                    rate = pay;
            //@param returns the name
            public String getName()
            return name;
            //@param returns the employee position
            public String getPosition()
            return position;
            //@param returns the hourly rate
            public double getRate()
            return rate;
            //@param returns the hours
            public double getHours()
            return hours;
            //get a new name
            //@param newName is the new name to be entered
            public void setName (String newName)
                    name = newName;
            //get a raise
            //@param inc is the amount to be increased
            public void getARaise (double inc)
                    rate += inc;
            //get the time worked
            //@param time is the amount of hours worked
            public void work (double time)
                    hours += time;
            //get the amount paid
            //@param rate is the amount of money
            public double getPaid ()
                   if ( hours > 40 )
                       double payment = rate*hours*40 + 1.5*rate*(hours-40);
                       double payment = rate * hours;
                    hours = 0.0;
            //compare employees
            //check if name, position and rate are the same
            public boolean equals (HourlyEmployee other)
            return name.equals (other.name)
                && position.equals (other.position)
                && rate == other.rate;
            //This method returns a string
            // with the name, position and rate of the employee
            public String toString()
                String myString = "HourlyEmployee[name =" + name
                        + "][position = " + position + "][rate= "
                        + rate + "]";
    }Now I have 2 problems:
    - The method getPaid is specified to return a double and gives me the error "missing return statement". How can I make it return a double?
    - The public String toString gives me the same error, I don't know why
    Any help?

  • Extending classes and constructors

    Hi,
    I am extending a class like this:
    public class MyTreeCellRenderer extends CheckableTreeCellRenderer
         public MyTreeCellRenderer()
    The super class has a constructor:
    public class CheckableTreeCellRenderer extends DefaultTreeCellRenderer
    public CheckableTreeCellRenderer()
    checkStyle = CHECKMARK;
    But I cannot instantiate my newly created class. What is the reason for this? Something wrong with the constructors?
    ERROR MESSAGE:
    symbol : constructor MyTreeCellRenderer ()
    location: class MyTreeCellRenderer
              MyTreeCellRenderer renderer = new MyTreeCellRenderer();

    Didn't you define the constructor of MyTreeCellRendered with some arguments?

  • Academic Question about Classes Method and Constructor

    Given the similarity between the Constructor class and the Method class, why don't they have a common super class for the methods they have in common that are unique to them?

    sledged wrote:
    jschell wrote:
    sledged wrote:
    I've found that the most common reason for invoking a constructor or method through reflection is because you don't know what you need until runtime, commonly because what you want can vary based on context, or is otherwise being specified external to the bit of code that uses reflection. Not true. The fact that I don't need it until runtime never means I don't know what I need.Never? Then your experiences with the reflection API have been different than mine. Either that or I wasn't very clear. Let's take Apache Commons BeanUtils;
    It doesn't matter how you access a class. You can't use it unless
    1. You have a goal in mind
    2. That object in some way fulfills that goal.
    3. You know how that object fulfills that goal.
    And as I already pointed out you can't use a JFrame for a JDBC driver. Simple as that. Nor can I create a new class that implements, for example, ProC (Oracle method to embed access into C code) using my own idiom despite that it provide database access. It MUST match what jdbc expects.
    Sometimes it's not even clear before runtime whether a constructor's needed or a method.
    I disagree. That isn't true in any OO language.Perhaps not out the box, but it can be true when using certain tools built from the OO language. Let me continue using the Spring framework as an example. It does not know whether to use a method or a constructor to instantiate any bean defined in the XML configuration metadata until that XML file is read and it determines whether or not a given bean definition has the "factory-method" attribute. The XML file in not read until runtime, therefore with any given bean defined therein, Spring does not know until runtime whether to use a constructor or method.Not apt at all.
    As I already said those are two different idioms. Spring supports them because they are used to solve different problems not because they wish constructors didn't exist.
    >
    The basis of OO is the "object". You can't have a method without the object in the conceptual OO model. (And in Smalltalk that is always true.)
    True, but one may not always care how the "object" is provided. When the method [Properties.load(InputStream)|http://java.sun.com/javase/6/docs/api/java/util/Properties.html#load%28java.io.InputStream%29] is called, it isn't going to care whether the InputStream argument was instantiated by one of the FileInputStream constructors, or if it came from a [URL.openStream()|http://java.sun.com/javase/6/docs/api/java/net/URL.html#openStream%28%29] method call. It'll work with either regardless of their respective origins.
    That of course has nothing to do with anything. Unless you are suggesting that construction in any form should not exist.
    A factory is not a constructor.I'm not saying it is. I'm just pointing out a number of the similarities between the two.
    So? There are many similarities between RMI and JDBC but that doesn't mean that they should be the same.
    With your argument you can claim that construction doesn't exist because any method, regardless of intent, that uses 'new' would eliminate the need for construction. And that isn't what happens in OO languages.I wouldn't claim that construction doesn't exist in any OO language. But I do know that in ECMAScript construction exists on the basis of whether or not a method is called with the 'new' operator. So in ECMAScript a single method can also be a constructor.
    And in C++ I can entirely circumvent the object construction process. Actually I can do that in JNI as well.
    I would still be a bad idea.
    >
    They are not interchangable.Normally, no, but with a high enough level of abstraction, they can become interchangeable. Again, the Spring framework is a great example. It doesn't care if a method or a constructor is used, and it won't know which one has been chosen until runtime. I don't even think Spring checks the return type of a method, so you could use a void return type method. (Although I don't know what that would buy you because the bean would always be set to null, but still...)
    No.
    Based on that argument every possible programming problem could be solved by simply stating that one must implement the "doit()" method. One just need to generalize it enough.
    Different APIs exist because there are in fact differences not because there are similarities.
    Over generalization WILL lead to code that is hard to maintain. Actually generalization itself, even when done correctly, can lead to code that is actually more complex.
    Because construction is substantially different than calling a method. In all OO languages.Yes, construction is different, but the actual call to a constructor and a method is only syntactically different with the presence of the 'new' operator. With reflection the difference is between calling Method.invoke() and Constructor.newInstance(), and, as I mentioned earlier, there's enough similarity between the two methods that they could be called by a single method specified by a common super class.Which does not alter the fact that the process of achieving the result is fundamentally different.

  • Final class and private constructor

    Whats the difference in a final class and a class with private constructot?
    If we can make a class non-extendable by just giving private constructor then whats the advantage of final class? (I know final is very useful for many other things but just want to get info in this contaxt)

    You can extend a class with a private constructor,I'm not sure about that. The compiler will complain.
    KajThat depends on the signature of the private constructor.
    If it's the no-arg constructor and you don't declare another constructor which you explicitly call from your derived class you will indeed get an error.
    If however you never call it (and there's no way it can implicitly get called) from a derived class there should be no problem.
    class Private1 {
         private int q;
         private Private1() {
         public Private1(int i) {
              q = i;
         public void print() {
              System.out.println(q);
    public class Public1 extends Private1 {
         public Public1() {
              super(1);
         public static void main(String[] args) {
              new Public1().print();
    }for example compiles and runs perfectly.
    But remove the call "super(1);" from the constructor and it will fail to compile.

  • I don't know what's wrong with my code. it's about class and object.

    * This is generic type of Person
    package myManagement;
    * @author roadorange
    public class Person {
    private String SS;
    private String firstName;
    private String lastName;
    private String middleName;
    private String phoneNumber;
    private String address;
    private String birthDay;
    public void setSS (String SS) {
    this.SS = SS;
    public String getSS() {
    return SS;
    public void setFirstName (String firstName) {
    this.firstName = firstName;
    public String getFirstName() {
    return firstName;
    public void setLastName (String lastName) {
    this.lastName = lastName;
    public String getLastName() {
    return firstName;
    public void setMiddleName (String middleName) {
    this.middleName = middleName;
    public String getMiddleName() {
    return middleName;
    public void setPhoneNumber (String phoneNumber) {
    this.phoneNumber = phoneNumber;
    public String getPhoneNumber() {
    return phoneNumber;
    public void setAddress (String address) {
    this.address = address;
    public String getAddress() {
    return address;
    public void setBirthDay (String birthDay) {
    this.birthDay = birthDay;
    public String getBirthDay() {
    return birthDay;
    public void Person() {
    SS = "1234567890";
    this.firstName = "abc"; //test the keyword "this"
    this.lastName = "xyz";
    middleName = "na";
    phoneNumber = "123456789";
    address = "11-11 22st dreamcity ny 11111";
    birthDay = "11-11-1980";
    public void print() {
    System.out.println("Display Database\n"
    + "Social Security Number: *********" + "\n"
    + "First Name: " + getFirstName() + "\n"
    + "Middle Name: " + getMiddleName() + "\n"
    + "Last Name: " + getLastName() + "\n"
    + "Phone Number: " + getPhoneNumber() + "\n"
    + "Address: " + getAddress() + "\n"
    + "getBirthDay: " + getBirthDay() );
    package myManagement;
    //this class is used to test other class or test other object
    public class testClass extends Person{
    public static void main(String[] args) {
    Person obj1 = new Person();
    obj1.print();
    System.out.println(obj1.getFirstName()); //test the object
    Result:
    Display Database
    Social Security Number: *********
    First Name: null
    Middle Name: null
    Last Name: null
    Phone Number: null
    Address: null
    getBirthDay: null
    null
    i don't know why it's all null. i assign something in the default constructor. it shouldn't be "null".
    does anyone know why?

    when you create 2 class using netbean editor, person.java and test.java
    i never compile person.java.
    when i finish typing these 2 class and i just right click test.java and run.
    my question is do i need to compile person.java before i run test.java directly??
    does Netbean compile it automatically when i run test.java first time?
    i add another constructor Person constuctor with one parameter in Person.java and create 2nd object to test the 2nd constuctor and run.
    All the codes work, so does the first default constructor. i don't why is that.
    Then i removed what i added and restore back to where it didn't work before and test again. it works.
    @_@. so weird.
    problem solved. thank you
    Edited by: roadorange on Feb 25, 2008 7:43 PM

  • Why do we intialize other classes in constructor ????

    Please see the question below:
    class MThread extends Thread {
    private Abc mfact = null;
    private Xyz mo = null;
    private Pro sts = null;
    * Constructor.
    public MThread(Abc mfact, Xyz mo ) { *// do i have to pass Pro here from calling method so that i can initialize in constructor in order to use its method like record ???*
    this.mfact = mfact;
    this.mo = mo;
    public somemethod() {
    sts.record();
    public void somemethod1() {
    mo.create();
    ***************************************************Another Class******************************************************
    public class Xyz{
    // Some code here
    // this class calls Mthread and creates 10 such Threads sth like
    for (int i = 0; i < 10; i++) {
    mThreads[i] = new MThread(mfact, mo;
    ***********Another Class ****************
    public class Pro {
    // some code
    public synchronized record() {
    rat ++;
    Explanation :
    Xyz calls Mthread 10 times to create such threads.
    Mthread has method that class Pro for stats recording
    Mthread also uses other class files to do some functioning of its own.
    Question:
    Please see the question in the constructor of Mthread ??
    for using method like record in Pro. do i have to initialize that in the constructor of Mthread ??
    because other class like Abc initializes itself in the construtor??
    Why do we have to initialize some class in constructor ?? I don't get it ?? Also when i press F3 (Open declaration ) on record call in somemethod ()
    .. it properly opens the file of class Pro and points to my sychronized method in that class ??
    CONFUSED... Please help ..
    Thank you

    javanewbie83 wrote:
    To morgair:
    thats right..so actually my question was do i need to change the requiremensts of the constructor so i can pass in the value of class Pro from the calling method.
    Do i need to do that. is that compulsory to use one of its methods
    ThanksYes, somehow you have to get visibility to your object that you want to use. If it's not passed in, then you have to have it in some global context with reference to where you want to use it.
    class myClass{
      A a;
      B b;
      C c;
      myClass(A a, B b, C c){
        this.a = a;
        this.b = b;
        this.c = c;
      public void myMethod(){
        c.doSomething(a, b);
    // This can be done since a and b are supplied as arguments to the constructor
    // but also consider this:
    class myClass{
      A a;
      B b;
      C c;
      myClass(A a, B b){
        this.a = a;
        this.b = b;
        c = new C();
      public void myMethod(){
        c.doSomething(a, b);
    //this will also work but c is a local variable
    //also consider this:
    class myOuterClass{
      A a;
      B b;
      C c;
      myOuterClass(){
        a = new A();
        b = new B();
        c = new C();
        //do stuff
      public void someStuff(){ 
        myInnerClass p = new myInnerClass(a, b);
        p.myMethod();  //this will also work since c is defined in myOuterClass
      class myInnerClass{
        A a;
        B b;
        myInnerClass(A a, B b){
          this.a = a;
          this.b = b;
        public void myMethod(){
          c.doSomething(a, b);
    }Note: this example is supplied off the top of my head without being tried in my IDE, but should show the concepts even if my fat fingers have hit the wrong keys.

Maybe you are looking for

  • Import/Export from Access MDB to Oracle DB

    Dear Friends, I need to import a huge table from access to Oracle. I tried to export the file from MS Access to Oracle, it is giving error. I tried another way of doing , i first exported the data to SQL server and then using Export/Import utility of

  • SAP Database is in dedicated or shared

    Hi Gurus I have a doubt. Our SAP Database is working on dedicated or shared mode. when i was passing thro some oracle documents i have read as per tnsnames.ora file we could come to know whether the dedicated or shared mode. I have checked our SAP sy

  • Regarding :Modifying the partition key column

    Hi, I have Create one table.At that time i did range partition on one column(callend).these table has 1000 millions records.Now I want to chage that partiion on another column (callstart) .How can i do this. Kindly provide me suggestion Regards.

  • Best way to manage pictures on HDD? Sorry I'm new to this...

    Please excuse what could be a dumb question, but after 20years of using Windows, I have move to my first Mac ever, and to be honest I absolutley love it and wish I'd done it earlier, although am struggling getting used to menu's etc, but after 20yrs

  • Problem with running cpu at the rite speed!!

    hi everyone,      i just change my mb to KT3-Ultra a month ago( i had a asuu A7V266-E before) with amd Athlon 1700+ everything work fine and runs very smooth on my windows xp ...but! i just find out that my cpu is just running at 1.10 ghz. after i ch