<img height="1" width="1" src="https://www.facebook.com/tr?id=1276476679054620&amp;ev=PageView &amp;noscript=1">

Week 3: Inheritance & Polymorphism

09/25/2015

Last week the students at Zip Code Wilmington were introduced to Java. From that point on they have been going full speed. Although they may feel a bit too overwhelmed to realize it, what they have accomplished in the span of a week is incredible.


Our last blog post talked about creating Java objects, their properties, their methods and utilizing finally utilizing them. Although the zipcoders have long moved on from that point, we will continue to take this blog in linear motion for at least one more blog post. The next step in Java for you readers, is expanding on the objects you learned about and created last week. The following concepts we will discuss are fairly simple and straightforward.



Look at the class below. Some of you may recognize it from last week:



[code]

public class Person {
    private String name;
    private int age;
    // a “String” is simply made  up of characters (chars) put  together
    // it is a built-in Java class
    public Person(String name,  int age) {
        this.name = name;
        this.age = age;
    }
    public void describeSelf() {
        System.out.println("My name  is " + this.name + ". I am " +  this.age + " years old.");
    }
}

[/code]

This class doesn’t do much; it allows you to set a name and age for someone as well as call a method that describes the person. Surely, this is not reflective of a real person. While it’s true that all persons have a name and age and could describe themselves in some way or another, this is not what we limit ourselves to. People are complex creatures with many different attributes spanning across the population. Having just a name, age, and description simply will not do. So what do we do? We can add to more to the class!


Before we add to our class however, we need context. By context, I mean something to model our Person class on. This isn’t specific to programming. In the real world, if you were trying to describe a person you would most likely be doing so in relation to a topic such as a potential date for a friend or a candidate for a job. We simply don’t want to list all possible descriptions of a Person as that list would be endless. I will use the context of a small community that consists of some intelligent scientists, brave law-enforcers, and, creative artists.


Now we can begin adding to this class. Let’s (vaguely) list some properties and actions that our three distinct persons of this community possess and can perform. Remember actions have parentheses at the end of their name and may take parameters in the parentheses.


For the scientists we have:

  • ScientificProject favoriteProject
  • useScientificMethod(Project project)
  • solveReallyComplexMathProblem()
  • receiveAward(Award award)

For the law-enforcers:

  • DangerousMission favoriteMission
  • performWeaponTraining()
  • arrestPerp(Perp perp)
  • receiveAward(Award award)

And finally the artists:

  • Artwork favoriteArtwork
  • createElaborateArtwork()
  • addStyle(Object object)
  • receiveAward(Award award)
With all the methods laid out, we can update our person class…or can we? We’ve listed different methods and fields for each kind of person in our community. Not all of our persons will useScientificMethod() or createElaborateArtwork().  However, all will receiveAward(Award award). We cannot just throw in all the methods in the class. Well, we can but that goes against OOP (Object-Oriented Programming from last week’s blog). Remember OOP is there to help you write better, readable code.


We will now introduce another concept in OOP called inheritance. You inherit traits from your parents. In other words, you share characteristics with them. All humans inherit from the mammal group as do other mammals, obviously. Cars and boats share similarities - they are both vehicles that transport objects. Everything can be traced back to a top level entity or abstraction - inheritance.


In OOP, inheritance is ubiquitous. Why? Well let’s look at our Person class and our persons again. We need a way to separate the different persons into their own class object but still remain Person objects. We can create standalone classes similar to the way we created a Person class but then we would have to repeat methods and fields in each class. That’s a waste of memory and time. Besides, if we do that, there would be no way to show the relationship between the different persons.


In reality, we may be so different at a glance but we are all still persons and we can see that by tracing our steps back in history, religion, science, art, e.t.c. Now before this post turns into something straight out of Buddha’s journal, here are the three separate classes all inheriting from the Person class:
SciencePerson class

[code]

public class SciencePerson extends Person {
    private ScientificProject  favoriteProject;
    public SciencePerson(String name, int age, ScientificProject favoriteProject) {
        this.setName(name);
        this.setAge(age);
        this.favoriteProject =  favoriteProject;
    }
    public void useScientificMethod(Project project) {
        // implementation
    }
    public Solution  solveReallyComplexMathProblem() {
        // implementation that  returns a Solution
    }
}

[/code]

LawEnforcerPerson class

[code]

public class  LawEnforcerPerson extends  Person {
    private DangerousMission  favoriteMission;
    public LawEnforcerPerson( String name, int age,  DangerousMission  favoriteMission) {
        this.setName(name);
        this.setAge(age);
        this.favoriteMission = favoriteMission;
    }
    public Result performWeaponTraining() {
        // implementation that  returns his/her training Result
    }
    public void arrestPerp(Perp perp) {
        // implementation that does  something with the Perp
    }
}

[/code]

ArtistPerson class

[code]

public class ArtistPerson  extends Person {
    private Artwork  favoriteArtwork;
    public ArtistPerson(String  name, int age, Artwork  favoriteArtwork) {
        this.setName(name);
        this.setAge(age);
        this.favoriteArtwork =  favoriteArtwork;
    }
    public Artwork  createElaborateArtwork() {
        // implementation that  returns his/her elaborate Artwork
    }
    public void addStyle(Object  object) {
        // implementation that adds  style to the passed in Object
    }
}

[/code]

Without spending much time on the individual classes, you inherit from a class by using the extends keyword in Java. Classes that extend from another class are known as  subclasses. With extension done, you have access to anything public in the Person class such as the describeSelf() method as well as the receiveAward(Award award) I just placed in below. I did this because all Persons (for now at least) can receive awards. Here is the updated Person class:

[code]

public class Person {
    private String name;
    private int age;
    // a “String” is simply made  up of characters (chars) put  together
    // it is a built-in Java class
    public Person(String name,  int age) {
        this.name = name;
        this.age = age;
    }
    public void describeSelf() {
        System.out.println("My name  is " + this.name + ". I am " +  this.age + " years old.");
    }
    public void receiveAward( Award award) {
        System.out.println("Thank you  so much. I am did am honored  to be a recipient of the " + award.toString() +  " award.");
    }
    // the below methods are  setters and getters (accessor  methods)
    // Don't be alarmed. Read the  name of the methods and their
    // implementation carefully.
    // All they do is provide an  interface for
    // retrieving and altering  the 'name' and 'age’ fields.
    // Remember those fields are  private and they cannot be  edited directly.
    // Not even subclasses (more  on this below) have direct  access to them.
    // These methods provide a  way to access them from  subclasses.
    // 'return' specifies that  the method should give back  the
    // specified variable. So ' return name' will return the ' name'
    // variable of this class.  Notice that 'getAge()' and ' getName()'
    // have types 'int' and ' string' next to them,  respectively.
    // This specifies the return  type of a method.
    public void setName(String  name) {
        this.name = name;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
}

[/code]

Before you go, I want to throw one more Java concept at you. Look at this (again) updated ArtistPerson class:

[code]

public class ArtistPerson  extends Person {
    private Artwork  favoriteArtwork;
    public ArtistPerson(String  name, int age, Artwork  favoriteArtwork) {
        this.setName(name);
        this.setAge(age);
        this.favoriteArtwork =  favoriteArtwork;
    }
    public Artwork  createElaborateArtwork() {
        // implementation that  returns his/her elaborate  artwork
    }
    public void addStyle(Object  object) {
        // implementation that adds  style to the passed in Object
    }
    @Override
    public void describeSelf() {
        System.out.println("My name  is " + this.name + ". I am an  artist and have been one for "  + this.age + " years now.");
    }
    @Override
    public void receiveAward( Award award) {
        System.out.println("This  award is the best award an  Artist could receieve. I am  truly honored.");
    }
}

[/code]

Notice the ArtistPerson class now has it’s own unique implementation of describeSelf() and receiveAward(Award award). Furthermore, those methods have the@Override keyword directly above them. This is known as polymorphism in OOP. By overriding it’s superclass’s method, it can provide a much more specific implementation which Java will use rather than that of its superclass.

[content_band inner_container="true" padding_top="10px" padding_bottom="10px" border="none" bg_pattern="http://www.zipcodewilmington.com/wp-content/uploads/Triangles__1441830476_50.73.209.90-compressor.jpg"]

Want to learn more Java? Check out more about our curriculum and apply today!

[/content_band]

curriculum inheritance JAVA polymorphism round-up

Comments