Applying Method Overriding Java Help

Applying Method Overriding

Let’s look at a more practical example that uses method overriding. The following  program creates a super class called Figure that stores the dimensions of various two-dimensional objects. It also defines a method called area that computes the area of an object. The program derives two sub classes from Figure. The first is Rectangle and the second is Triangle. Each of these sub classes overrides area( ) so that returns the area of a rectangle and a triangle, respectively.

Using Abstract Classes

There are situations in which you will want to define a super class that declares the
structure of a given abstraction without providing a complete implementation of every  method ..That is, sometimes you will want to create a super class that only destines a generalized form that will b~ shared by all of its sub classes, leaving it to each subclass to fill in the details. Such a class determines the nature of the methods that the sub classes must implement. One way this situation can occur is when a super class is unable to create a meaningful implementation for a method. This is the case with the class Figure used in the preceding example; The definition of area( is simply a placeholder. It will not compute and display the area of any type of object:
As you will see as you create your own class libraries, it is not uncommon for a method to have no meaningful definition in the context of its super class. You can
handle this situation two ways. One way, as shown in the previous example, is to
simply have it report a warning message. While this approach can be useful in certain situations-such as debugging-it is not usually appropriate. You may have methods which must be overridden by the subclass in order for the subclass to have any  meaning. Consider the class Triangle. It has no meaning if area( ) is not defined. In this case, want some way to ensure that a subclass does, indeed, override all necessary methods. Java’s solution to this problem is the abstract method. You can require that certain methods be overridden by sub classes by specifying the abstract type modifier. These methods’ are sometimes referred to as sub because they have no implementation specified in the super class. Thus, a . subclass must override them-it cannot simply use the version defined in the super class, To declare abstract method, use this general form

JavaHelpOnline.com

  • Feel free to send us an inquiry, we will reply back in hours.
 

Verification

Posted on September 17, 2014 in Inheritance

Share the Story

About the Author

Back to Top