Learning Java
Custom Search

Previous Next

Inheritance

Inheritance is the concept by which a new class can be created from a previous class, in which case it is called a subclass of the previous class. The previous class is the superclass of the new class. The subclass inherits the attributes and the methods of the superclass. The subclass can have additional attributes and methods not included in the superclass. It can also override the methods of the superclass.

Below, we have a class called Person. We are going to create a new class called Athlete from our Person class. Athlete will inherit all the attributes and methods from Person.

class Person {
    double weight;

    Person(double weightx) {
	weight = weightx;
    }

    void bodyChange(String eatx, String exercisex) {
	if (eatx.equals("l")) {
	    weight = weight * .90;
	} else if (eatx.equals("h")) {
	    weight = weight * 1.10;
	}

	if (exercisex.equals("l")) {
	    weight = weight * 1.05;
	} else if (exercisex.equals("h")) {
	    weight = weight * .95;
	}
    }
}

The new class, Athlete extends Person, which means it will contain the same attributes and methods that Person contains. Person has a contructor that sets the weight. We will call that constructor from Athlete's constructor by using the super() method. If used, it must be the first statement in the constructor in the subclass.

class Athlete extends Person {
    String PerformanceRecord;
    String Sport;
    boolean IsFamous;

    Athlete(String asport, boolean afamous, double aweight) {
	super(aweight);
	Sport = asport;
	IsFamous = afamous;
    }

    void InterviewForJeansAd() {
	if (weight < 220 && IsFamous)  
	    System.out.println("Send letter requesting an interview.");
    }

    public static void main(String args[]) {
	double wt = 190;
	Athlete BabeRuthJr = new Athlete("baseball", true, wt);
	BabeRuthJr.bodyChange("h", "h");
	BabeRuthJr.InterviewForJeansAd();
    }
}

The object BabeRuthJr was instantiated from the class Athlete in main. It now has access to the variables and the methods in both Person and Athlete.

In this statement BabeRuthJr accesses the method of its superclass, Person.

    BabeRuthJr.bodyChange("h", "h");

In this statement BabeRuthJr accesses the method of Athlete.

    BabeRuthJr.InterviewForJeansAd();

Previous Next

Steps In Learning

Contact us

Copyright © 2008      N. Nelson      All Rights Reserved