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?

Similar Messages

  • Inherit / extend class calls constructor...

    Hi,
    Class A extends class B like so:
    public class A extends B{}
    Why is class B's constructor called? I thought when A extends
    B, A gets all of B's methods and variables, great; but I don't need
    the constructor called because class B has already been created. I
    just want class A to inherit all of B's methods and variables. Can
    a class have two constructors, so when I extend class B an empty
    constructor is called but when I instantiate it the constructor
    with code is called?
    I feel like I’m missing something here.
    Thanks,
    4dplane

    Yep you are missing something. :)
    The constructor is just that -- it builds each instance of
    the class, puts it together if you will. Without a call to the
    superclass's constructor you won't get all its properties, methods,
    etc.
    You'll notice that the B constructor is even call first. That
    is to make sure that everything is ready and accessable to A
    It sounds like whatever you are trying to do isn't really a
    good candidate for extension.. Fill us in a bit more and perhaps we
    can come up with some ideas..

  • 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:)

  • Extending classes and overriding methods

    If I have a class which extends another, and overrides some methods, if I from a third class casts the extending class as the super class and calls one of the methods which gets overrided, is it the overrided method or the method of the superclass which get executed?
    Stig.

    Explicit cast can't enable the object to invoke super-class's method. Because dynamic binding is decided by the instance. The cast can just prevent you from using methods only defined in sub-class, but it does not let the object to use super-class's method, if the method's been overrided. Otherwise, the polymophism, which is one of the most beautiful feature of Object-Oriented thing, can't be achieved. As far as I know, the only way to use super-class's method is the super keyword in the sub-class, and seems no way for an object to do the same thing (I may wrong, since I haven't read the language spec).
    here's a small test:
    public class Test {
    public static void main(String[] args){
    A a = new B();
    a.method();
    ((A)a).method();
    class A{
    public void method(){
    System.out.println("A's method");
    class B extends A{
    public void method(){
    System.out.println("B's method");
    The output is:
    B's method
    B's method

  • 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

  • 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.

  • 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.

  • When extending class do constructors get implemented as well

    Say i need to call a list as an object and it was an extension of another list. Would the constructor be the same but with the extended list name??
    For example:
    First class:
    public class ListR
            //variables
         public ListModelR()
              trackCount = 0;
              firstTrack = null;
              lastTrack = null;
         }///rest of code...
    Would the class that extended this hav a constructor of its class name or would i have to reference ListModelR?
    Thanks James

    You cant have a constructor that is different from your classes name.
    class A
         public A()
              int a = 5;
    class B
         public B()
              super(); //executes the super class's default constructor
    }

  • 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);
    }%

  • JSP - difference between extending class and importing class

    In the following scenario
    class A
    private static String con;
    Case 1
    ==========
    class B extends A
    Case 2
    ===========
    import A;
    class C
    A objA = new A;
    What will be the difference in Case 1 and Case 2 on accessing the variable con.
    thanx
    Venki

    >
    If i am not wrong, the above line should be private
    static variables are not inherited.
    NO, AFAIK, static variables, private or otherwise arent inherited. Please note that doesnt mean, its not available in the sub-class. Infact it is. However you cannot override or hide them ie polymorphism isnt applicable to static members which is what , IMO, inheritance is all about. Its logical, when you think about it, polymorphism is applicable for objects and static is a class thinggy, has nothing to do with objects.
    cheers,
    ram.

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • 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

  • 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?

Maybe you are looking for