Computer Science Canada

one question.. [ inheritance ]

Author:  TheNewOne [ Sun Oct 24, 2004 10:50 pm ]
Post subject:  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. Smile
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. Razz

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!

Author:  wtd [ Mon Oct 25, 2004 1:22 am ]
Post subject: 

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.

code:
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.

code:
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.

code:
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.

Author:  TheNewOne [ Mon Oct 25, 2004 7:05 am ]
Post subject: 

Great! I have understood alot. Thank you very much.


: