Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 one question.. [ inheritance ]
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
TheNewOne




PostPosted: 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!
Sponsor
Sponsor
Sponsor
sponsor
wtd




PostPosted: Mon Oct 25, 2004 1:22 am   Post subject: (No 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.
TheNewOne




PostPosted: Mon Oct 25, 2004 7:05 am   Post subject: (No subject)

Great! I have understood alot. Thank you very much.
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 3 Posts ]
Jump to:   


Style:  
Search: