Java inheritence

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Anvesh Tummala
    New Member
    • Jan 2014
    • 5

    Java inheritence

    Code:
    class animal(){ void A()}
    class carnivore extends animal(){void B()}
    class x{
    public static void main(){ 
    animal a= new carnivore();
    carnivore b= new animal();
    a.B();   // Does it show error
    b.A();   // does it show error
    
    }
    Last edited by Rabbit; Jan 3 '14, 04:14 PM. Reason: Please use [CODE] and [/CODE] tags when posting code or formatted data.
  • Nepomuk
    Recognized Expert Specialist
    • Aug 2007
    • 3111

    #2
    Hi Anvesh Tummala!

    Have you tried? Does the above code work? If not, where are there errors shown and why?

    Comment

    • Anvesh Tummala
      New Member
      • Jan 2014
      • 5

      #3
      @nepomuk
      Hi,

      animal a= new carnivore(); it is correct as we can assign an subclass object to super class object
      carnivore b= new animal(); it is an error(incompati ble assignment) we cannot assign a super class object to a sub class object. REASON: the sub class may have more methods and instance variables than super class, when we assign super class object to subclass object those extra methods and variables are not initialized.
      a.B(); yes its an error as the reference is only a type of super class , it can't access the methods of sub class, even though the object is a sub class type. it is showing compilation error.
      a.B(); it is blunder mistake.

      Comment

      • Nepomuk
        Recognized Expert Specialist
        • Aug 2007
        • 3111

        #4
        Very good. A few additions:
        • b.A() would work if b were initialized correctly, e.g.
          Code:
          carnivore b = new carnivore();
          b.A();
        • it is possible to access the methods of a subtype if you cast an object to that subtype (and the cast is legal); so while a.B() doesn't work,
          Code:
          ((carnivore) a).B();
          will.
        • It is the convention in Java to begin class names with an upper case letter and method names with lower case letters. Also, descriptive names are much better for variables (and method names). So following those conventions your code would look like this:
          Code:
          class Animal { void doA(); }
          
          class Carnivore extends Animal { void doB(); }
          
          class X {
              public static void main() {
                  Animal animal = new Carnivore();
                  Carnivore carnivore = new Animal();
                  animal.doB(); // Does it show error
                  carnivore.doA(); // does it show error
              }
          }

        Comment

        • Anvesh Tummala
          New Member
          • Jan 2014
          • 5

          #5
          very useful additions

          Comment

          Working...