Thursday,
June 14
This session covers the readings in and Day 4: Working with Objects and Day 6: Creating Classes and Methods |
Review of
Session 3 and Short Quiz
Object-Oriented Programming (continued)
|
Assignment:
design exercise |
Lecture 4
In this lecture, you learn about three fundamental concepts of OOP: inheritance, polymorphism, and encapsulation. You also learn about two related concepts: abstract methods and interfaces.
Inheritance is a fundamental concept of OOP. It facilitates the re-use of code. You only have to make the minimal changes, or diffs, to the existing class, to specialize (or extend) the class.
For example, the class Shape is generic to all shapes.
Oval, Triangle, Rectangle, Pentagon, and Hexagon can inherit from Shape.
Square can inherit from Rectangle.
Circle can inherit from Oval.
In each case, the subclass is a specialized version of the superclass.
/*
* This class is an abstract class. An abstract class cannot
* be instantiated, but it can be used as a template and be
* specialized (extended) by subclasses.
*
* The definition of Shape is a a sort of 'contract'
* or constraint that when you create
* a specialized version of Shape, it will have
* to provide the two methods, getParameter and getArea.
*/
public abstract class Shape
{
private Color myColor;
public Shape(Color color)
{
myColor = color;
}
public void setColor(Color color)
{
myColor = color;
// I can override whatever default color
attribute
// this method inherents from the abstract class:
// for example myColor = blue;
}
public Color getColor()
{
return myColor;
}
/**
* This method should return the perimeter of the shape
*/
public abstract float getPerimeter(); // no body
/**
* This method should return the area of the shape
*/
public abstract float getArea(); // no body
}
/**
* This class is a specialization of the Shape class and represents
* a Circle.
*/
public class Circle extends Shape
{
// we define a constant related to the Circle class, PI
public static final float PI = 3.1415927;
// here is a private instance variable, the radius
private float radius = 0.0;
/**
* Constructor of the Circle class, take the radius as parameter
*/
public Circle(float radius)
{
// here the term radius refers to the parameter of this
// constructor
// the instance variable has the same name as the
// parameter of this method, therefore we have to
// use the 'this' keyword, because the instance variable
// is masked by the argument.
this.radius = radius;
}
public float getPerimiter()
{
return 2 * PI * radius;
}
public float getArea()
{
return PI * radius * radius;
}
}
Note: Unlike C++, Java only supports single inheritence.
Note: If the current class overrides the superclass, but for one method in the current class you want to use a method of the superclass with the same name, use the keyword "super". "Super" refers to the class higher up in the hierarchy from which the current class inherits the method or attribute.
An abstract class is a class that cannot be instantiated. Inside of an abstract class, you can define methods as abstract, which means that you do not provide a body. An abstract method should not have any curly braces. Instead the declaration of the method must be followed by a semicolon.
An abstract class can also implement methods.
Analogy: Think of an abstract
class as a contract that requires that the subclasses implement the methods.
An interface is similar to an abstract class. However, there are important differences:
An interface, unlike an abstract class, cannot implement any of its methods
An interface can only define methods that are abstract
An interface can only define variables that are PUBLIC
A method can inherit (keword: extends) from only one class (abstract or not), but a method can implement (keyword: implements) any number of interfaces
Let us define Shape as an interface:
public interface Shape
{
public void setColor(Color color);
public Color getColor();
public abstract float getPerimeter();
public abstract float getArea();
}
Analogy:
An interface forces the user of a class to comply with a
"contract".
The interface tells you what are the different methods you will be able access (or implement as the developer), without giving you any idea of the actual implementation of it. It frees you of the need to know the 'HOW', you only need to know the 'WHAT'.
When you drive a car, you don't really care about knowing how the gas pedal interacts with the injection system, you just want to know that when you press the right pedal your car will go faster.
Note: If you store different
shapes in an array, and you define a Draw() method both for the interface and
for each subclass, when you call
Shapes[i].Draw();
the compiler uses the Draw() method of the specific object at that index
in the array.
POLYMORPHISM
Polymorphism enables a method to work with objects that extend the base class. For example, we know that there are many subclasses of the base class, Shape. the printAllPerimeters methods depends upon Java's support for polymorphism to enable this method to work with an array that mixes together circles, squares, and triangles. You do not need separate methods for printPerimetersForSquares, printPerimetersForCircles, and printPerimetersForTriangles. Even if one your programmers creates a new shape, say, the Dodecahedron, which has 12 sides, your method will work. In this limited sense, polymorphism can make your code design "future-proof" and more open to changes.
Example:
public void printAllPerimeters(Shape[] shapes)
{
for (int i = 0; i < shapes.length; i ++)
{
System.out.println(shapes[i].getPerimeter());
}
}
ENCAPUSULATION
Encapsulation is about hiding and protecting how a method works. In general, when you create a class, you do not want to expose all the aspects of that class to other classes. Another programmer on the team might inadvertantly damage your code.
To make encapsulation easy, Java provides the concept of visibility for methods, attributes, and classes.
There are three levels of encapsulation:
public means accessible from everywhere
protected means accessible from the members of the same class, its subclasses, and the members of the same package (a means of grouping classes)
private means accessible only from within the same class
public class Car
{
public void accelerate() // accessible to the user
{
increaseFuelInjection();
updateSpeedometer();
}
private void increaseFuelInjection() // hidden from the user
{
}
private void updateSpeedometer() // hidden from the user
{
}
}
Example: A ChessBoard class might have an array of arrays to reference the attributes that correspond to the x- and y- coordinates of each piece. Each piece would have its own set of movement methods. The CheshPiece interface would have the MoveTo() method, but each specific piece would have a different implementation of its movement behavior, that is, a different set of methods. The MoveTo method returns a boolean that tells the ChessBoard whether or not to allow the piece to move to a specific position on the board. Note: You could have a Point object.
class Castle extends Piece { boolean canMoveTo(x0, y0, xf, yf); // more code }
Make class stubs for the library management design project:
Maybe the classes could include the following:
book (check out for 2 weeks)
magazine (check out for 1 day)
reference (cannot be checked out)
customer
librarian (who helps customers find books and magazines)
clerk (who checks out materials to customers and also puts materials back on the shelves)
professor (who can put books and magazines on 2-hour reserve)
library card
fine (fee you must pay when you book is overdue)
You can show the class in a flat system, or in a system with an inheritance hierarchy.
In the hierarchy,
--both librarian and clerk could inherit from employee
--library card and fine could be attributes of customer
--both professor and customer could inherit from user
--book, magazine, and reference could inherit from material
Or, design a different arrangement for the library's business needs.
_________________________
course
homepage course
calendar