Results 1 to 4 of 4
  1. #1
    powerpravin is offline Member
    Join Date
    Mar 2011
    Posts
    12
    Rep Power
    0

    Exclamation Inheritance issue

    I declared a class 'Item' as follows:
    ---------------------------------
    class Item{
    double boltCost=20;
    public double cost(){
    return 0.0;
    }

    }
    ---------------------------------

    And then extended it in class 'Bolt'
    ---------------------------------
    class Bolt extends Item{
    double boltCost=10;

    Bolt(){//-->Constructor

    boltCost = 10;
    }

    public double cost(){

    return boltCost;
    }
    }

    -----------------------
    When trying to execute the following commands

    Item i = new Bolt()
    i.boltCost


    i.boltCost returns 20 which is the value from Item class.

    But when run the cost method

    i.cost()

    it returns 10 that is from Bolt class..
    :confused:
    Please help

  2. #2
    lovelesh is offline Senior Member
    Join Date
    Nov 2010
    Location
    Delhi
    Posts
    135
    Blog Entries
    1
    Rep Power
    0

    Smile

    That's the correct behavior of java runtime.

    You have hidden the parent class' boltCost variable and moreover you are changing that variable in the contructor. That is why you are getting the value 10 for boltCost.

    I suggest reading some basic articles on java programming for this.

    Java Tutorial: Home

  3. #3
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default

    The more important question is why does the Item class have a variable called boltCost? Not every Item is going to be a Bolt.

  4. #4
    powerpravin is offline Member
    Join Date
    Mar 2011
    Posts
    12
    Rep Power
    0

    Default

    Thanks for replying.
    I was just curious, otherwise there is no need of Bolt in Item class

Similar Threads

  1. JPA Inheritance
    By videanuadrian in forum New To Java
    Replies: 1
    Last Post: 01-10-2011, 06:44 AM
  2. Inheritance
    By Nerijus in forum New To Java
    Replies: 5
    Last Post: 04-20-2010, 03:47 AM
  3. Inheritance
    By gpio in forum Advanced Java
    Replies: 14
    Last Post: 11-20-2009, 10:41 AM
  4. Simple Inheritance issue...
    By AWE in forum New To Java
    Replies: 3
    Last Post: 07-27-2009, 09:56 PM
  5. inheritance
    By itaipee in forum New To Java
    Replies: 6
    Last Post: 01-20-2009, 08:18 PM

Tags for this Thread

Posting Permissions

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