Results 1 to 4 of 4
  1. #1
    kaka is offline Member
    Join Date
    Sep 2010
    Posts
    5
    Rep Power
    0

    Default how to initialize base class variable without creating object for that?

    class A{
    protected int i;
    }
    class B extends A{
    }
    class C extends B{

    -------------------//howto initialize i=10;

    }

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,776
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by kaka View Post
    class A{
    protected int i;
    }
    class B extends A{
    }
    class C extends B{

    -------------------//howto initialize i=10;

    }
    If you're not creating any objects you can't initialize any 'i' (it belongs to an object) but if you're instantiating a new object C you can initialize member variable 'i' in C's constructor.

    kind regards,

    Jos

  3. #3
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    It's worth noting that if you want a variable to exist without a base object, you may want to use static variables.

    More on those here: http://download.oracle.com/javase/tu...variables.html

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default

    Quote Originally Posted by JosAH View Post
    If you're not creating any objects you can't initialize any 'i' (it belongs to an object) but if you're instantiating a new object C you can initialize member variable 'i' in C's constructor.

    kind regards,

    Jos
    Though I would have made 'i' private, and used a constructor in A which takes a value for 'i'.

Similar Threads

  1. Replies: 2
    Last Post: 06-22-2010, 05:29 AM
  2. Replies: 2
    Last Post: 03-08-2010, 11:29 AM
  3. How to show class initialize data in JSP ?
    By tking88 in forum New To Java
    Replies: 0
    Last Post: 03-07-2010, 10:17 AM
  4. Replies: 16
    Last Post: 05-08-2008, 10:45 PM
  5. Creating object of Type Object class
    By venkatv in forum New To Java
    Replies: 3
    Last Post: 07-17-2007, 04:33 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •