question on overriding

Post Reply
GatesWinkler
Posts: 6
Joined: Thu Sep 23, 2010 10:13 pm

question on overriding

Post by GatesWinkler » Thu Sep 30, 2010 9:53 pm

Hi, for my second friendly monster, I made a class i called gnome. but I'm a little confused about the instruction to override the parent class. After some research, Ive done the following, which has the gnome do a different action than give gifts through the gift class, but I'm not certain that this is what was meant. I just wanted to knw if I was on the right track.

class Gnome extends FriendlyMonster {

PImage gnomeImg = loadImage("gnome.jpg");
public Gnome() {
super.gifts.add("the gnome wants to help you get a discount on your travel planning");
}

public void giveGifts() {
println(super.gifts);
}

public void render(int x, int y) {
super.render(x,y);
image(gnomeImg, x,y,w,h);
}
}

angus
Posts: 43
Joined: Fri Apr 02, 2010 1:54 pm

Re: question on overriding

Post by angus » Fri Oct 01, 2010 12:15 pm

Hi yes, I probably should have used the word "extend" instead of "override." Often when you use the "extends" keyword to inherit from a class you end up overriding some of the methods. You don't need a special keyword to override a method, you simply make the function signature look the same. -Angus

Code: Select all

public class Parent {
   public Parent() {}
 
   public int manipulateNumberMethod(int number) {
      println("I am a method in Parent!"); 
      return number * 2;
}

//the extends keyword indicates that we are inheriting from the class "Parent"
public class Child extends Parent {
   public Child() {}
 
   //since we are using the same function signature as the method in the "Parent" class
   //Java can polymorphically find this method.
   public int manipulateNumberMethod(int number) {
       println("I am a method in Child!");       
       return number / 2;
}

Post Reply