Home

Inheritance

 

Introduction to Inheritance

 

Definition

 
Volley Ball Football Basketball Handball Golf
Volley Ball Football Basketball Handball Golf

The primary characteristic of the objects on the above pictures is that they are balls used in different sports. Another characteristic they share is that they are round. On the other hand, although these balls are used in sport, one made for one sport cannot (or should not) be used in another sport (of course, it is not unusual for a footballer to mess with a basketball on a lawn but it is not appropriate). The common characteristics of these objects can be listed in a group like a Java class. The class would appear as:

class Ball {
    TypeOfSport;
    Size;
}

If you were asked to create a class to represent these balls, you may be tempted to implement a general class that defines each ball. This may be a bad idea because, despite their round resemblance, there are many internal differences among these balls. Programming languages like Java provide an alternate solution to this type of situation.

Inheritance consists of creating a class whose primary definition or behavior is based on another class. In other words, inheritance starts by having a class that can provide behavior that other classes can improve on.

Practical LearningPractical Learning: Introducing Inheritance

  1. Start NetBeans and create a Java Application named Geometry4
  2. To create a new class, in the Projects window, under the Geometry4 folder, right-click the Geometry4 sub-folder -> New -> Java Class...
  3. Set the Name to Circle and click Finish
  4. Change the file as follows:
     
    package geometry4;
    
    public class Circle {
        private double radius;
    
        public Circle() {
            this.radius = 0.00;
        }
    }

Class Derivation

As you may have guessed, in order to implement inheritance, you must first have a class that provides the fundamental definition or behavior you need. There is nothing magical about such a class. It could appear exactly like any of the classes we have used so far. Here is an example:

File: Circle.java
public class Circle {
    private double radius;

    public double getRadius() {
	return radius;
    }

    public void setRadius(double value)  {
        if( radius < 0 )
	    radius = 0.00;
	else
	    radius = value;
    }

    public double calculateDiameter() {
        return radius * 2;
    }

    public double calculateCircumference() {
        return calculateDiameter() * 3.14159;
    }
	
    public double calculateArea() {
        return radius * radius * 3.14159;
    }
}
Circle
File: Exercise.java
public class Exercise {
    public static void main(String[] args) {
	Circle round = new Circle();
	round.setRadius(25.55);

	System.out.println("Circle Characteristics");
	System.out.printf("Side:          %f\n", round.getRadius());
	System.out.printf("Diameter:      %f\n",
		round.calculateDiameter());
	System.out.printf("Circumference: %f\n", 
		round.calculateCircumference());
	System.out.printf("Area:          %f\n", 
		round.calculateArea());
    }
}

This would produce:

Circle Characteristics
Side:          25.550000
Diameter:      51.100000
Circumference: 160.535249
Area:          2050.837806

The above class is used to process a circle. It can request or provide a radius. It can also calculate the circumference and the area of a circle. Now, suppose you want to create a class for a sphere. You could start from scratch as we have done so far. On the other hand, since a sphere is primarily a 3-dimensional circle, and if you have a class for a circle already, you can simply create your sphere class that uses the already implemented behavior of a circle class. Creating a class that is based on another class is also referred to as deriving a class from another. The first class serves as parent or base. The class that is based on another class is also referred to as child or derived.

To create a class based on another, you use the following formula:

modifier class NewChild extends BaseClass {
      // Body of the new class
}

In this formula, you start with the class keyword followed by a name from your class. On the right side of the name of your class, you must type the : operator, followed by the name of the class that will serve as parent. Of course, the BaseClass class must have been defined; that is, the compiler must be able to find its definition. Based on the above formula, you can create a sphere class based on the earlier mentioned Circle class as follows:

class Sphere extends  Circle {
      // The class is ready
}

After deriving a class, it becomes available and you can use it just as you would any other class. Here is an example:
File: Circle.java
public class Circle {
    private double radius;

    public double getRadius() {
	return radius;
    }

    public void setRadius(double value)  {
        if( radius < 0 )
	    radius = 0.00;
	else
	    radius = value;
    }

    public double calculateDiameter() {
        return radius * 2;
    }

    public double calculateCircumference() {
        return calculateDiameter() * 3.14159;
    }
	
    public double calculateArea() {
        return radius * radius * 3.14159;
    }
}
File: Sphere.java
class Sphere extends  Circle {
}
File: Exercise.java
public class Exercise {
    public static void main(String[] args) {
	Circle round = new Circle();
	round.setRadius(25.55);

	System.out.println("Circle Characteristics");
	System.out.printf("Side:          %f\n", round.getRadius());
	System.out.printf("Diameter:      %f\n",
		round.calculateDiameter());
	System.out.printf("Circumference: %f\n",
		round.calculateCircumference());
	System.out.printf("Area:          %f\n",
		round.calculateArea());

	Sphere ball = new Sphere();
	ball.setRadius(25.55);

	System.out.println("\nSphere Characteristics");
	System.out.printf("Side:          %f\n", ball.getRadius());
	System.out.printf("Diameter:      %f\n",
		ball.calculateDiameter());
	System.out.printf("Circumference: %f\n",
		ball.calculateCircumference());
	System.out.printf("Area:          %f", ball.calculateArea());
    }
}

This would produce:

Circle Characteristics
Side:          25.550000
Diameter:      51.100000
Circumference: 160.535249
Area:          2050.837806

Sphere Characteristics
Side:          25.550000
Diameter:      51.100000
Circumference: 160.535249
Area:          2050.837806

When a class is based on another class, all public members of the parent class are made available to the derived class. While other methods and classes can also use the public members of a class, the difference is that the derived class can call the public members of the parent as if they belonged to the derived class. That is, the child class does not have to "qualify" the public members of the parent class when these public members are used in the body of the derived class. This is illustrated in the following program:
File: Circle.java
public class Circle {
    private double radius;

    public double getRadius() {
	return radius;
    }

    public void setRadius(double value)  {
        if( radius < 0 )
	    radius = 0.00;
	else
	    radius = value;
    }

    public double calculateDiameter() {
        return radius * 2;
    }

    public double calculateCircumference() {
        return calculateDiameter() * 3.14159;
    }
	
    public double calculateArea() {
        return radius * radius * 3.14159;
    }

    public void ShowCharacteristics() {
	System.out.println("Circle Characteristics");
	System.out.printf("Side:          %f\n", getRadius());
	System.out.printf("Diameter:      %f\n",
		calculateDiameter());
	System.out.printf("Circumference: %f\n",
		calculateCircumference());
	System.out.printf("Area:          %f\n",
		calculateArea());
    }
}
File: Sphere.java
class Sphere extends  Circle {
    public void ShowCharacteristics() {
	// Because Sphere is based on Circle, you can access
	// any public member(s) of Circle without qualifying it(them)
	System.out.println("\nSphere Characteristics");
	System.out.printf("Side:          %f\n", getRadius());
	System.out.printf("Diameter:      %f\n",
		calculateDiameter());
	System.out.printf("Circumference: %f\n",
		calculateCircumference());
	System.out.printf("Area:          %f", calculateArea());
    }
}
File: Exercise.java
public class Exercise {
    public static void main(String[] args) {
	Circle round = new Circle();

	round.setRadius(25.55);
	round.ShowCharacteristics();

	Sphere ball = new Sphere();

	ball.setRadius(25.55);
	ball.ShowCharacteristics();
    }
}

This would produce the same result as earlier.

Practical LearningPractical Learning: Deriving a Class

  1. To create a new class, in the Projects window, under the Geometry4 folder, right-click the Geometry4 sub-folder -> New -> Java Class...
  2. Set the Name to Cylinder and click Finish
  3. Change the file as follows:
     
    package geometry4;
    
    public class Cylinder extends Circle {
        private double height;
        
        public Cylinder() {
            
        }
    
        public double getHeight() {
            return height;
        }
        
        public void setHeight(double height) {
            height = height;
        }
    }
 

Inheritance in

C#
C++
C++/CLI
 

Characteristics of Inheritance

 

Overriding Derived Methods

You may have noticed in the above example that the derived class produced the same results as the base class. In reality, inheritance is used to solve various object-oriented programming (OOP) problems. One of them consists of customizing, adapting, or improving the behavior of a method of the parent class. For example, although both the circle and the sphere have an area, their areas are not the same.

A circle is a flat surface but a sphere is a volume, which makes its area very much higher. Since they use different formulas for their respective area, you should implement a new version of the area in the sphere.

When deriving one class from another class, you should be aware of the fields and methods of the base class so that, if you know that the parent class has a certain behavior or a characteristic that is not conform to the new derived class, you can do something about that.

Providing a new version of a method that exists in the parent is referred to as overriding it.

To override a method, start it with the expression @Override. Then create the new version of the method. It must use the same return type, the same name, and the same arguments, if any, of the parent class. Here is an example:

class Circle {
    private double radius;

    public double getRadius() {
	return radius;
    }

    public void setRadius(double value)  {
        if( radius < 0 )
	    radius = 0.00;
	else
	    radius = value;
    }

    public double calculateDiameter() {
        return radius * 2;
    }

    public double calculateCircumference() {
        return calculateDiameter() * 3.14159;
    }
	
    public double calculateArea() {
        return radius * radius * 3.14159;
    }
}

class Sphere extends  Circle {
    @Override
    public double  calculateArea() {
	    return 4 * getRadius() * getRadius() * 3.14159;
    }
}

public class Exercise {
    public static void main(String[] args) {
	Circle round = new Circle();
	round.setRadius(25.55);

	System.out.println("Circle Characteristics");
	System.out.printf("Side:          %f\n", round.getRadius());
	System.out.printf("Diameter:      %f\n",
		round.calculateDiameter());
	System.out.printf("Circumference: %f\n",
		round.calculateCircumference());
	System.out.printf("Area:          %f\n",
		round.calculateArea());

	Sphere ball = new Sphere();
	ball.setRadius(25.55);

	System.out.println("\nSphere Characteristics");
	System.out.printf("Side:          %f\n", ball.getRadius());
	System.out.printf("Diameter:      %f\n",
		ball.calculateDiameter());
	System.out.printf("Circumference: %f\n",
		ball.calculateCircumference());
	System.out.printf("Area:          %f", ball.calculateArea());
    }
}

This would produce:

Circle Characteristics
Side:          25.550000
Diameter:      51.100000
Circumference: 160.535249
Area:          2050.837806

Sphere Characteristics
Side:          25.550000
Diameter:      51.100000
Circumference: 160.535249
Area:          8203.351224

Notice that, this time, the areas of both figures are not the same even though their radii are similar.

Besides customizing member variables and methods of a parent class, you can add new members as you wish. This is another valuable feature of inheritance. In our example, while a circle is a flat shape, a sphere has a volume. In this case, you may need to calculate the volume of a sphere as a new method or property of the derived class. Here is an example:

class Circle {
    private double radius;

    public double getRadius() {
	return radius;
    }

    public void setRadius(double value)  {
        if( radius < 0 )
	    radius = 0.00;
	else
	    radius = value;
    }

    public double calculateDiameter() {
        return radius * 2;
    }

    public double calculateCircumference() {
        return calculateDiameter() * 3.14159;
    }
	
    public double calculateArea() {
        return radius * radius * 3.14159;
    }
}

class Sphere extends  Circle {
    @Override
    public double  calculateArea() {
	    return 4 * getRadius() * getRadius() * 3.14159;
    }

    public double calculateVolume() {
        return 4 * 3.14159 * getRadius() * 
	       getRadius() * getRadius() / 3;
    }
}

public class Exercise {
    public static void main(String[] args) {
	Circle round = new Circle();
	round.setRadius(25.55);

	System.out.println("Circle Characteristics");
	System.out.printf("Side:          %f\n", round.getRadius());
	System.out.printf("Diameter:      %f\n",
		round.calculateDiameter());
	System.out.printf("Circumference: %f\n",
		round.calculateCircumference());
	System.out.printf("Area:          %f\n",
		round.calculateArea());

	Sphere ball = new Sphere();
	ball.setRadius(25.55);

	System.out.println("\nSphere Characteristics");
	System.out.printf("Side:          %f\n", ball.getRadius());
	System.out.printf("Diameter:      %f\n",
		ball.calculateDiameter());
	System.out.printf("Circumference: %f\n",
		ball.calculateCircumference());
	System.out.printf("Area:          %f\n",
		ball.calculateArea());
        System.out.printf("Volume:        %f", ball.calculateVolume());
    }
}

This would produce:

Circle Characteristics
Side:          25.550000
Diameter:      51.100000
Circumference: 160.535249
Area:          2050.837806

Sphere Characteristics
Side:          25.550000
Diameter:      51.100000
Circumference: 160.535249
Area:          8203.351224
Volume:        69865.207924
 

Protected Members

To maintain a privileged relationship with its children, a parent class can make a member available only to classes derived from it. With this relationship, some members of a parent class have a protected access level. Of course, as the class creator, it is your job to specify this relationship.

To create a member that derived classes can access, type the protected keyword to its left. If you declare of the class, you can call still access its public members. Here are examples:

class Person {
    private String _name;
    private String _gdr;

    public Person() {
	this._name = "Not Available";
	this._gdr    = "Unknown";
    }

    public Person(String name, String gender) {
	this._name = name;
	this._gdr  = gender;
    }

    protected String getFullName() {
	return _name;
    }

    protected void setFullName(String value) {
	_name = value;
    }

    protected String getGender() {
	return _gdr;
    }

    protected void setGender(String value) {
	_gdr = value;
    }
		
    public void show() {
	System.out.printf("Full Name: %s\n", this.getFullName());
	System.out.printf("Gender:    %s", this.getGender());
    }
}

public class Exercise {
    public static void main(String[] args) {
	Person man = new Person("Hermine Sandt", "Male");

	System.out.println("Staff Member");
	man.show();
    }
}

This would produce:

Staff Member
Full Name: Hermine Sandt
Gender:    Male

If you create a class member and mark it as protected, the other classes of the same application (package) and the classes derived from that parent class can access those protected members. This means that, unlike C++ and C#, classes not derived from that class but that belong to the same program can access the protected members of the class. Here are examples:

class Person {
    private String _name;
    private String _gdr;

    public Person() {
	this._name = "Not Available";
	this._gdr    = "Unknown";
    }

    public Person(String name, String gender) {
	this._name = name;
	this._gdr  = gender;
    }

    protected String getFullName() {
	return _name;
    }

    protected void setFullName(String value) {
	_name = value;
    }

    protected String getGender() {
	return _gdr;
    }

    protected void setGender(String value) {
	_gdr = value;
    }
}

public class Exercise {
    public static void main(String[] args) {
	Person man = new Person();

	man.setFullName("Gertrude Binam");
	man.setGender("Female");

	System.out.println("Staff Member");
	
	System.out.printf("Full Name: %s\n", man.getFullName());
	System.out.printf("Gender:    %s", man.getGender());
    }
}

This would produce:

Staff Member
Full Name: Gertrude Binam
Gender:    Female

Practical LearningPractical Learning: Using Protected Members of Parent Class

  1. Access the Circle.java file
  2. To create a protected member, change the file as follows:
    package geometry4;
    
    public class Circle {
        protected double radius;
    
        public Circle() {
            this.radius = 0.00;
        }
        
        public Circle(double radius) {
            this.radius = radius;
        }
        
        public double getRadius() {
    	return radius;
        }
    
        public void setRadius(double value)  {
            if( radius < 0 )
    	    radius = 0.00;
    	else
    	    radius = value;
        }
    
        public double calculateDiameter() {
            return radius * 2;
        }
    
        public double calculateCircumference() {
            return calculateDiameter() * 3.14159;
        }
    	
        public double calculateArea() {
            return radius * radius * 3.14159;
        }
    }
  3. Access the Cylinder.java file
  4. To use a protected member, change the file as follows:
    package geometry4;
    
    public class Cylinder extends Circle {
        private double height;
        
        public Cylinder() {
            
        }
    
        public double getHeight() {
            return height;
        }
        
        public void setHeight(double height) {
            height = height;
        }
    
        public double calculateLateralArea() {
            return 2 * 3.14159 * radius * height;    
        }
    
        public double calculateTotalArea() {
            return 2 * 3.14159 * radius * (height + radius);
        }
    
        public double calculateVolume() {
            return 3.14159 * radius * radius * height;
        }
    }
  5. Access the Main.java file and change it as follows:
    package geometry4;
    import java.util.Scanner;
    
    public class Main {
    
        private static Cylinder create()
        {
            double r,  h;
            Cylinder cup = new Cylinder();
            Scanner scnr = new Scanner(System.in);
    
            System.out.print("Enter the Radius: ");
            r = scnr.nextDouble();
            System.out.print("Enter the Height: ");
            h = scnr.nextDouble();
            
            cup.setRadius(r);
            cup.setHeight(h);
            return cup;
        }
        
        private static void show(Cylinder cyl) {
            System.out.println("\nCylinder Characteristics");
            System.out.printf("Radius:       %f\n", cyl.getRadius());
            System.out.printf("Height:       %f\n", cyl.getHeight());
            System.out.printf("Base Area:    %f\n", cyl.calculateArea());
            System.out.printf("Lateral Area: %f\n",
                    cyl.calculateLateralArea());
            System.out.printf("Total Area:   %f\n",
                    cyl.calculateTotalArea());
            System.out.printf("Volume:       %f\n", cyl.calculateVolume());  
        }
        
        public static void main(String[] args) {
            Cylinder tube = create();
            show(tube);
        }
    
    }
  6. Execute the application to test it. Enter the radius as 44.48 and the height as 24.86:
    Enter the Radius: 44.48
    Enter the Height: 24.86
    
    Cylinder Characteristics
    Radius:  44.480000
    Height:  24.860000
    Base:    6215.542824
    Lateral: 6947.769542
    Total:   19378.855189
    Volume:  154518.394603
 
 
 
 

Previous Copyright © 2008-2012, FunctionX Next