Results 1 to 4 of 4
  1. #1
    krishanu is offline Member
    Join Date
    May 2011
    Posts
    20
    Rep Power
    0

    Default need help on object creation

    HI,
    class A {
    //some code
    }
    class B extends A
    {
    //some code
    }
    class Demo
    {
    public static void main (String args[])
    {
    A a = new B();// object will create ....any explanation???
    //but
    B b = new A(); //will not work why??

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,457
    Rep Power
    25

    Default

    What did the compiler error message say?

    B can have methods etc that are not in A.
    Then b.aMethodInOnlyB() would fail.

  3. #3
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    Welcome, please use [code][/code] tags when posting code. Also, please provide a question, not just a code dump :)

    Edit: Sorry, I didn't see your questions in the comments at first glance!

  4. #4
    jing-yi is offline Member
    Join Date
    May 2011
    Posts
    35
    Rep Power
    0

    Default

    Hi,

    A a = new B(); is acceptable during compilation because B is the subclass of A. This mean B always consist of the methods in A.
    B b = new A(); is not acceptable during compilation because A "may not have" relationship with B. A may not consist the methods in B.

    It will return you Type mismatch during compilation time.

    You could solve the compilation error by putting in casting, where now B b = (B)new A();

    However, during run-time, system return you class cast exception as A
    1) not inherit from B.
    2) not equal to B.

    Thanks
    Jing-yi

Similar Threads

  1. Doubt in Package-Object creation
    By t0mat0 in forum New To Java
    Replies: 1
    Last Post: 06-02-2010, 06:39 AM
  2. String Object Creation
    By indranil in forum New To Java
    Replies: 1
    Last Post: 04-13-2010, 11:30 AM
  3. object creation
    By enygma in forum Java Applets
    Replies: 0
    Last Post: 01-05-2010, 10:01 AM
  4. Object creation and construstion
    By abimaran in forum New To Java
    Replies: 8
    Last Post: 12-15-2009, 09:58 AM
  5. Object creation and memory issues
    By bugger in forum New To Java
    Replies: 11
    Last Post: 11-29-2007, 12:56 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
  •