0% found this document useful (0 votes)
14 views19 pages

6.lab 06-OOP

Uploaded by

aishorjoshuchi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views19 pages

6.lab 06-OOP

Uploaded by

aishorjoshuchi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Object Oriented Programming: Java

Laboratory 06

Laboratory 6: ArrayList, Inheritance and Polymorphism

Submission Due: End of laboratory class, demonstrate and submit the file on Google
classroom at least 10 minutes before the end of laboratory class.

Total Marks = 5 marks for each lab.

Marks will be given only to students who attend and participate during the 2 hours’ laboratory
class. Demonstration and Submission on google classroom is mandatory as evidence of
participation.

Description of the laboratory exercise:

Method Overloading
Methods of the same name can be declared in the same class, as long as they have different sets of
parameters (determined by the number, types and order of the parameters)—this is called
method overloading. When an overloaded method is called, the compiler selects the
appropriate method by examining the number, types and order of the arguments in the call.
Method overloading is commonly used to create several methods with the same name that
perform the same or similar tasks, but on different types or different numbers of arguments. For
example, Math methods abs, min and max are overloaded with four versions each:

1. One with two double parameters.


2. One with two float parameters.
3. One with two int parameters.
4. One with two long parameters.

Our next example demonstrates declaring and invoking overloaded methods.

Example for practice:


public class MethodOverload
{

Prepared by: Dr. Md Ashraf Uddin, Associate Professor, Jagannath University, Dhaka
Object Oriented Programming: Java
Laboratory 06

Example for practice:

Prepared by: Dr. Md Ashraf Uddin, Associate Professor, Jagannath University, Dhaka
Object Oriented Programming: Java
Laboratory 06

Prepared by: Dr. Md Ashraf Uddin, Associate Professor, Jagannath University, Dhaka
Object Oriented Programming: Java
Laboratory 06

Introduction to Collections and Class ArrayList

The Java API provides several predefined data structures, called collections, used to store
groups of related objects in memory. These classes provide efficient methods that organize, store
and retrieve your data without requiring knowledge of how the data is being stored. This reduces
application-development time. You’ve used arrays to store sequences of objects. Arrays do not
automatically change their size at execution time to accommodate additional elements. The
collection class

ArrayList<T> (package java.util) provides a convenient solution to this problem—it can


dynamically change its size to accommodate more elements. The T (by convention) is a
placeholder—when declaring a new ArrayList, replace it with the type of elements that you want
the ArrayList to hold. For example,

ArrayList<String> list;

declares list as an ArrayList collection that can store only Strings. Classes with this kind of
placeholder that can be used with any type are called generic classes. Only nonprimitive types can be
used to declare variables and create objects of generic classes. However, Java provides a mechanism—
known as boxing—that allows primitive values to be wrapped as objects for use with generic
classes. So, for example,

ArrayList<Integer> integers;

Prepared by: Dr. Md Ashraf Uddin, Associate Professor, Jagannath University, Dhaka
Object Oriented Programming: Java
Laboratory 06
declares integers as an ArrayList that can store only Integers. When you place an int value into
an ArrayList<Integer>, the int value is boxed (wrapped) as an Integer object, and when you get
an Integer object from an ArrayList<Integer>, then assign the object to an int variable, the int
value inside the object is unboxed (unwrapped).

Example for practice:

Prepared by: Dr. Md Ashraf Uddin, Associate Professor, Jagannath University, Dhaka
Object Oriented Programming: Java
Laboratory 06

Prepared by: Dr. Md Ashraf Uddin, Associate Professor, Jagannath University, Dhaka
Object Oriented Programming: Java
Laboratory 06

Inheritance, Super class, and sub class


Object-oriented programming allows you to define new classes from existing classes. This is called inheritance.

Inheritance is an important and powerful feature for reusing software.

Superclasses and Subclasses


Often, an object of one class is an object of another class as well. For example, a CarLoan is a
Loan as are HomeImprovementLoans and MortgageLoans. Thus, in Java, class CarLoan can be
said to inherit from class Loan. In this context, class Loan is a superclass and class CarLoan is a
subclass. A CarLoan is a specific type of Loan, but it’s incorrect to claim that every Loan is a
CarLoan—the Loan could be any type of loan. List of several simple examples of superclasses
and subclasses—superclasses tend to be “more general” and subclasses “more specific.” For
example, the superclass Vehicle represents all vehicles, including cars, trucks, boats, bicycles and
so on. By contrast, subclass Car represents a smaller, more specific subset of vehicles.

University Community Member Hierarchy

Shape Hierarchy

Prepared by: Dr. Md Ashraf Uddin, Associate Professor, Jagannath University, Dhaka
Object Oriented Programming: Java
Laboratory 06

Public, Private and Protected access specifier


A class’s public members are accessible wherever the program has a reference to an object of that
class or one of its subclasses. A class’s private members are accessible only within the class itself.
In this section, we introduce the access modifier protected. Using protected access offers an
intermediate level of access between public and private. A superclass’s protected members can
be accessed by members of that superclass, by members of its subclasses and by members of
other classes in the same package—protected members also have package access.

All public and protected superclass members retain their original access modifier when they
become members of the subclass—public members of the superclass become public members of
the subclass, and protected members of the superclass become protected members of the
subclass. A superclass’s private members are not accessible outside the class itself. Rather, they’re
hidden from its subclasses and can be accessed only through the public or protected methods
inherited from the superclass.

Subclass methods can refer to public and protected members inherited from the superclass
simply by using the member names. When a subclass method overrides an inherited superclass
method, the superclass version of the method can be accessed from the subclass by preceding the
superclass method name with keyword super and a dot (.) separator.

The GeometricObject class is the superclass for Circle and Rectangle.

Example for practice:

Prepared by: Dr. Md Ashraf Uddin, Associate Professor, Jagannath University, Dhaka
Object Oriented Programming: Java
Laboratory 06

public class SimpleGeometricObject {


private String color = "white";
private boolean filled;
private java.util.Date dateCreated;

/** Construct a default geometric object */


public SimpleGeometricObject() {
dateCreated = new java.util.Date();
}

Prepared by: Dr. Md Ashraf Uddin, Associate Professor, Jagannath University, Dhaka
Object Oriented Programming: Java
Laboratory 06

Prepared by: Dr. Md Ashraf Uddin, Associate Professor, Jagannath University, Dhaka
Object Oriented Programming: Java
Laboratory 06

Prepared by: Dr. Md Ashraf Uddin, Associate Professor, Jagannath University, Dhaka
Object Oriented Programming: Java
Laboratory 06

/** Set a new height */


public void setHeight(double height) {
this.height = height;
}
/** Return area */
public double getArea() {
return width * height;
}

/** Return perimeter */


public double getPerimeter() {
return 2 * (width + height);
}
}

Prepared by: Dr. Md Ashraf Uddin, Associate Professor, Jagannath University, Dhaka
Object Oriented Programming: Java
Laboratory 06

Using the super Keyword


The keyword super refers to the superclass and can be used to invoke the superclass’s
methods and constructors.
A subclass inherits accessible data fields and methods from its superclass. Does it inherit
constructors? Can the superclass’s constructors be invoked from a subclass? This section
addresses these questions and their ramifications.
The this Reference, introduced the use of the keyword this to reference the calling object. The
keyword super refers to the superclass of the class in which super appears. It can be used in two
ways:
▪ To call a superclass constructor.
▪ To call a superclass method.

Prepared by: Dr. Md Ashraf Uddin, Associate Professor, Jagannath University, Dhaka
Object Oriented Programming: Java
Laboratory 06

Calling Superclass Constructors


A constructor is used to construct an instance of a class. Unlike properties and methods, the
constructors of a superclass are not inherited by a subclass. They can only be invoked from the
constructors of the subclasses using the keyword super.

The syntax to call a superclass’s constructor is:

super(), or super(parameters);

The statement super() invokes the no-arg constructor of its superclass, and the statement
super(arguments) invokes the superclass constructor that matches the arguments. The
statement super() or super(arguments) must be the first statement of the subclass’s
constructor; this is the only way to explicitly invoke a superclass constructor.

Constructor Chaining
A constructor may invoke an overloaded constructor or its superclass constructor. If neither is
invoked explicitly, the compiler automatically puts super() as the first statement in the
constructor. For example:

In any case, constructing an instance of a class invokes the constructors of all the superclasses
along the inheritance chain. When constructing an object of a subclass, the subclass constructor
first invokes its superclass constructor before performing its own tasks. If the superclass is
derived from another class, the superclass constructor invokes its parent-class constructor before
performing its own tasks. This process continues until the last constructor along the inheritance
hierarchy is called. This is called constructor chaining.

Prepared by: Dr. Md Ashraf Uddin, Associate Professor, Jagannath University, Dhaka
Object Oriented Programming: Java
Laboratory 06

The program produces the preceding output. Why? Let us discuss the reason. In line 3, new
Faculty() invokes Faculty’s no-arg constructor. Since Faculty is a subclass of Employee,
Employee’s no-arg constructor is invoked before any statements in Faculty’s constructor are
executed. Employee’s no-arg constructor invokes Employee’s second constructor (line 13).
Since Employee is a subclass of Person, Person’s no-arg constructor is invoked before any
statements in Employee’s second constructor are executed. This process is illustrated in the
following figure.

Calling Superclass Methods


The keyword super can also be used to reference a method other than the constructor in the

Prepared by: Dr. Md Ashraf Uddin, Associate Professor, Jagannath University, Dhaka
Object Oriented Programming: Java
Laboratory 06
superclass. The syntax is:
super.method(parameters);

You could rewrite the printCircle() method in the Circle class as follows:

public void printCircle() {


System.out.println("The circle is created " +
super.getDateCreated() + " and the radius is " + radius);
}

It is not necessary to put super before getDateCreated() in this case, however, because
getDateCreated is a method in the GeometricObject class and is inherited by the Circle class.
Nevertheless, in some cases, as shown in the next section, the keyword super is needed.

Overriding Methods

To override a method, the method must be defined in the subclass using the same signature and the same return
type as in its superclass.

A subclass inherits methods from a superclass. Sometimes it is necessary for the subclass to
modify the implementation of a method defined in the superclass. This is referred to as method
overriding. The toString method in the GeometricObject class returns the string representation
of a geometric object. This method can be overridden to return the string representation of a
circle. To override it, add the following new method in the Circle class.

public class CircleFromSimpleGeometricObject


extends SimpleGeometricObject {
// Other methods are omitted

// Override the toString method defined in the superclass


public String toString() {
return super.toString() + "\nradius is " + radius;
}
}

The toString() method is defined in the GeometricObject class and modified in the Circle
class. Both methods can be used in the Circle class. To invoke the toString method defined in
the GeometricObject class from the Circle class, use super.toString() (line 7). Can a subclass
of Circle access the toString method defined in the GeometricObject class using syntax such
as super.super.toString()? No. This is a syntax error. Several points are worth noting:

▪ An instance method can be overridden only if it is accessible. Thus a private method


cannot be overridden, because it is not accessible outside its own class. If a method
defined in a subclass is private in its superclass, the two methods are completely
unrelated.
▪ Like an instance method, a static method can be inherited. However, a static method
cannot be overridden. If a static method defined in the superclass is redefined in a
subclass, the method defined in the superclass is hidden. The hidden static methods can
be invoked using the syntax SuperClassName.staticMethodName.

Prepared by: Dr. Md Ashraf Uddin, Associate Professor, Jagannath University, Dhaka
Object Oriented Programming: Java
Laboratory 06

Overriding vs. Overloading


Overloading means to define multiple methods with the same name but different signatures. Overriding means to
provide a new implementation for a method in the subclass.

To override a method, the method must be defined in the subclass using the same signature and
the same return type. Let us use an example to show the differences between overriding and
overloading. In (a) below, the method p(double i) in class A overrides the same method defined
in class B. In (b), however, the class A has two overloaded methods: p(double i) and p(int i).
The method p(double i) is inherited from B.

When you run the Test class in (a), both a.p(10) and a.p(10.0) invoke the p(double i) method
defined in class A to display 10.0. When you run the Test class in (b), a.p(10) invokes the p(int
i) method defined in class A to display 10, and a.p(10.0) invokes the p(double i) method
defined in class B to display 20.0.

Note the following:


▪ Overridden methods are in different classes related by inheritance; overloaded methods
can be either in the same class or different classes related by inheritance.
▪ Overridden methods have the same signature and return type; overloaded methods have
the same name but a different parameter list.

To avoid mistakes, you can use a special Java syntax, called override annotation, to place
@Override before the method in the subclass. For example:

public class CircleFromSimpleGeometricObject


extends SimpleGeometricObject {
// Other methods are omitted

@Override
public String toString() {

Prepared by: Dr. Md Ashraf Uddin, Associate Professor, Jagannath University, Dhaka
Object Oriented Programming: Java
Laboratory 06
return super.toString() + "\nradius is " + radius;
}
}

This annotation denotes that the annotated method is required to override a method in the
superclass. If a method with this annotation does not override its superclass’s method, the
compiler will report an error. For example, if toString is mistyped as tostring, a compile error is
reported. If the override annotation isn’t used, the compile won’t report an error. Using
annotation avoids mistakes.

Exercise 1: (Student Inheritance Hierarchy) Draw an inheritance hierarchy for students at a


university similar to the hierarchy shown in Figure below. Use Student as the superclass of the
hierarchy, then extend Student with classes UndergraduateStudent and GraduateStudent.
Continue to extend the hierarchy as deep (i.e., as many levels) as possible. For example,
Freshman, Sophomore, Junior and Senior might extend UndergraduateStudent, and
DoctoralStudent and MastersStudent might be subclasses of GraduateStudent. After drawing the
hierarchy, discuss the relationships that exist between the classes. [Note: You do not need to
write any code for this exercise.]

Exercise 2: (Shape Inheritance Hierarchy) The world of shapes is much richer than the
shapes included in the inheritance hierarchy of Figure below. Write down all the shapes you can
think of—both two-dimensional and three-dimensional—and form them into a more complete
Shape hierarchy with as many levels as possible. Your hierarchy should have class Shape at the
top. Classes TwoDimensionalShape and ThreeDimensionalShape should extend Shape. Add
additional subclasses, such as Quadrilateral and Sphere, at their correct locations in the hierarchy
as necessary.

Prepared by: Dr. Md Ashraf Uddin, Associate Professor, Jagannath University, Dhaka
Object Oriented Programming: Java
Laboratory 06

Exercise 3: (Quadrilateral Inheritance Hierarchy) Write an inheritance hierarchy for


classes Quadrilateral, Trapezoid, Parallelogram, Rectangle and Square. Use Quadrilateral as the
superclass of the hierarchy. Create and use a Point class to represent the points in each shape.
Make the hierarchy as deep (i.e., as many levels) as possible. Specify the instance variables and
methods for each class. The private instance variables of Quadrilateral should be the x-y
coordinate pairs for the four endpoints of the Quadrilateral. Write a program that instantiates
objects of your classes and outputs each object’s area (except Quadrilateral).

End of the Laboratory☺

Prepared by: Dr. Md Ashraf Uddin, Associate Professor, Jagannath University, Dhaka

You might also like