
-----------------------------------
TheNewOne
Sun Oct 24, 2004 10:50 pm

one question.. [ inheritance ]
-----------------------------------
Hello, this is my first posting here but I have been a long time reader of this forum (Turing index). I have two questions that boggle my mind. :)
I've searched on the internet but it's pretty hard to understand everything they say because i don't know alot of the terminology they use.  I apparently have a simplistic mind. :P

The question:
I understnad that inheritance is a very important concept in programming, what is it actually? What is it in terms of class, superclass, and objects? Also what is overriding?

Many thanks!

-----------------------------------
wtd
Mon Oct 25, 2004 1:22 am


-----------------------------------
A class may inherit from a superclass.  The inherited class gains access to all public and protected aspects of the parent class.  Inheritance defines an is-a relationship between classes.  A child class may override anything it inherits from the parent class.

We start out with a very basic Dog class.

class Dog {
   private String name;

   public Dog(String initName) {
      name = initName;
   }

   public String bark() {
      return "Woof!";
   }
}

Now, we want a GuardDog class.  We've already got a Dog class, so why reinvent the whole thing?  Besides, a guard dog is a dog...

Assume a Person class.

class GuardDog extends Dog {
   // create a constructor for this class
   public GuardDog(String initName) {
      // just call the parent class' constructor
      super(initName);
   }

   public void attack(Person intruder) {
      System.out.println(bark());
      person.reduceHealth();
   }
}

And now, to demonstrate overriding, we create a sad MuteGuardDog class.  To do this we override "bark()" so that it returns an empty string.

class MuteGuardDog extends GuardDog {
   public MuteGuardDog(String initName) {
      super(initName);
   }

   public String bark() {
      return "";
   }
}

And to sum up... MuteGuardDog is a GuardDog is a Dog.  This of course also means that a MuteGuardDog is a Dog.

Anywhere your program would require a Dog you could use a child of the Dog class.

-----------------------------------
TheNewOne
Mon Oct 25, 2004 7:05 am


-----------------------------------
Great! I have understood alot. Thank you very much.
