INHERITANCE TOPICS - Objects, Classes, OOD and OOP - Object-Oriented Design: Basic Principles - Inheritance o Rules and facts about superclass/subclass o Constructors (superclass/subclass) o Protected members of a class o The Object class - Programming Samples o Inheritance: Class Rectangle - Class Box o Inheritance: Class Time - Class ExtendedTime OUTLINE 1. Objects,
Classes, OOD and OOP
- Object-oriented analysis, object-oriented design (OOD) and object-oriented programming (OOP) are based on entities known as objects. An object has a state (whose representation is hidden) and a defined set of operations that operate on that state. The state is represented as a set of object attributes. Operations associated with an object provide services to other objects (clients), which request these services when some computation is required. - The fundamental idea behind object-orientation is to combine into a single unit both data and the functions that operate on that data (encapsulation). An object’s functions or methods are the means of accessing that data. This data is actually hidden from the user or other programs. - Each object is an instance of a class. A class definition totally defines the behavior and attributes of objects of that particular class. - (Reminder) Some definitions: o Object. Objects encapsulate data and operations that need to be performed on that data. Objects have interfaces that only allow authorized operations to be performed on data (generally known as the access methods.) Thus data remains safe from malicious or inadvertent changes. Once defined, objects can be used as basic data types within a program. An object has a state, presents an interface and exhibits a behavior. The state is determined by the value of the object’s internal data, which results from the operations performed on that data by changing its state. The variables representing the internal state of an object are called instance variables. The collection of methods determines the object’s interface and behavior. Also called: class object or class instance; variable of type class o Class. A class is a generalized description of the characteristics of similar objects. It is a template from which objects may be created by invoking certain methods called the constructor methods. Constructor methods are generally called automatically when an object is instantiated and serve to allocate memory, initialize object state, etc. Similarly, when these objects are destroyed, destructor methods are automatically invoked which are generally used to release the allocated memory, close open files, perform garbage collection etc. Objects of the same class have common operations and therefore uniform behavior. Classes have one or more interfaces that specify the operations accessible to clients through that interface. A class body specifies code for implementing operations in the class interface. o Message. Messages are signals sent from one object to another that request the receiving object to execute one of its methods. Messages are similar to function/method calls, i.e., they tell an object which service or state change it should perform. o Methods. Methods are procedures contained within an object that are executed in response to a message. Depending upon the language, most or all of the communication between objects takes place by sending messages that invoke methods. - OOD o First step in the problem-solving process with an object-oriented approach = identify the components ("objects") which form the basis of the solution, and determine how these objects interact with each other. Example: video store inventory application - objects: videos and customers. o Next step: Specify for each object the relevant data and possible operations to be performed on that data. Example: video store inventory application - the data for a movie object may include the movie title, year released, type of movie, director, starring actors, number of copies in store, etc. Some operations on a movie object may include: how many copies not rented, list info for a movie, list info for movies with a common property (query), etc. o Remember that the fundamental idea behind object-orientation is to combine into a single unit both data and the methods that operate on that data. In OOD, the final program is a collection of interacting objects. o OOD has 3 basic principles: 1. Encapsulation 2. Polymorphism 3. Inheritance - A programming language that implements OOD is called an Object-Oriented Programming (OOP) language. - Advantages/Disadvantages of OOP · Advantages:
- Nevertheless, all of these problems are easily outweighed by the potential benefits of object-oriented technology. 2.
Object-Oriented Design: Basic Principles - Encapsulation o Definition: The ability to combine data and operations in a single unit (classes). An object therefore becomes a self-contained entity. Operations can directly access the data, but the internal state of an object cannot be manipulated directly. o Encapsulation is a form of information hiding (Information hiding = a form of abstraction --> separating the description of how to use a class from the details of the class’ implementation). Encapsulation allows changes to be made to the implementation of a system with minimal effects on the end user. It is a technique by which data is packaged together with its corresponding procedures (methods). The state data in an object is said to be encapsulated and therefore hidden from the outside world. This means that the internal data of an object can only be accessed through the message interface for that object. The way in which the internal data is accessed is hidden from the client. This is because it is neither required nor is it convenient that the designer of the application should be aware of the internal implementation details of the method invoked by a message. o Encapsulation is implemented using access control by using access/visibility modifiers (public - accessible by everyone, in particular public members are available to the client programmer; private - accessible only by the methods within the class; protected - to be discussed later) o Encapsulation separates interface from implementation § Interface: The visible parts of the class; they can be used and/or changed by the client/programmer. A class interface is defined by its public methods. § Implementation: The hidden parts of the class; they can be changed by the class creator without impacting any of the client code. In other words, the implementation cannot be corrupted by the client programmer. Private instance variables hide implementation details, promoting encapsulation. o NOTE: In general you should NOT provide accessors and mutators for all private instance variables. Encapsulation is best served with a limited class interface. o Advantages of using encapsulation: § Programmers that use a class do not need to know how the class is implemented, only how to use it § The information the client programmer needs to use the class is kept to a minimum § Class implementation may be changed with no impact on those who use the class - Polymorphism o Definition: The ability to use the same expressions to denote different operations. Polymorphism is a word of Greek origin that means having multiple forms. o Polymorphism refers to the ability to hide different implementations behind a common interface. With polymorphism, the same message can be interpreted differently by objects of different classes and therefore produce different but appropriate results. One of the most common examples of polymorphism is method overloading. An overloaded method appears to perform different activities depending upon the kind of data sent to it. The computer treats overloaded functions separately on the basis of the number of arguments and their types. Overloaded methods can simplify the task of a programmer by reducing the number of method names to be managed. o Polymorphism further reduces programming complexities by allowing common and unified interfaces for related operations. - Inheritance o Definition: Inheritance = the ability to create new data types from existing data types (in particular, create new classes from existing classes). In other words, specialized objects may be derived from more generic classes of objects. o Inheritance is a mechanism through which class definitions can be built up from other class definitions. If a class definition specifies a use of another class definition, it inherits the definition and may then customize this by adding further attributes and operations of its own. Moreover, the inheriting or the child class may redefine operations inherited from the parent class. o Multiple inheritance is also possible in which the class has several parents and it inherits the properties of all its parents (supported by C++, NOT supported by Java). The parent class is also known as a superclass whereas the child class may also be referred to as a subclass or a derived class. o With single inheritance (supported by Java), an inheritance hierarchy or tree is created. Here a class can inherit attributes from a single superclass. o With multiple inheritance, an inheritance network evolves rather than an inheritance hierarchy or an inheritance tree. o Effective software development relies on reusing existing code and inheritance is a useful mechanism for supporting code reuse. However, as classes are reused by implementing subclasses, the classes become more complex and more difficult to understand individual components. - Definition: is-a Relationship = a hierarchical connection where one category can be treated as a specialized version of another. Examples: a Car is a Vehicle, an Employee is a Person, a Student is a Person, a Polygon is a Figure, etc. -
Definition: Inheritance Hierarchy = a set of classes that can
share common code, connected by is-a relationships. Often drawn as a
downward tree of connected boxes or ovals representing classes. Example:
- In the tree-like hierarchical structure above, every square is a rectangle; every rectangle is a polygon; every polygon is a closed figure; every closed figure is a figure. - Definition: Inheritance = A way to define a new class based on a class that already exists (= a way to group related classes = a way to share code between two or more classes). The new class will inherit the characteristics of the existing class, but also provide some additional capabilities --> will make programming easier (reuse of code, avoid redundant code). Rather than create a completely new class from scratch, we can take advantage of inheritance and reduce software complexity. - Inheritance creates new classes by adding code to an existing class. The existing class is reused without modification. - Inheritance allows us to group classes into families of related types (Figure), allowing for the sharing of common operations and data. - The existing class is called a superclass (or parent class, or base class). The new class based on the superclass is called a subclass (or child class, or derived class). Each subclass, in turn, could become a superclass for a future subclass --> inheritance extends over several generations of classes (multiple levels of subclassing). The subclass receives a copy of every data and method members from its superclass, and then specializes the superclass. A common specialization is to extend the superclass with additional fields, methods, or both. - In the tree-like hierarchical structure above, the class Square is a subclass of Rectangle; the class Rectangle is a subclass of class Polygon; the class Polygon is a subclass of class Closed Figure; the class Closed Figure is a subclass of class Figure. The class Figure is the superclass and the classes Closed Figure, Open Figure, Polygon, etc. are subclasses. - Definition: Single inheritance = the process by which a subclass inherits characteristics from just one parent (subclass is derived from one existing superclass). Java supports single inheritance. - Definition: Multiple inheritance = the process by which a subclass inherits characteristics from more than one parent (subclass is derived from more than one existing superclass). Java does NOT support multiple inheritance. - Syntax: modifier(s)
class SubclassName extends SuperclassName modifier(s) Where modifier(s) could be public,
private or
protected (private by default). Example:
- Rules and facts about superclass/subclass:
1. If the subclass overrides a public method of the superclass ---> specify a call to the public method of the superclass by using super (reserved word in Java) followed by the dot operator followed by the method name and parameter list. Syntax: super.methodName(parameter list) Example: super.print(); The reserved word super is used to refer to the immediate superclass of a class. It is only valid to use super to invoke a method from a direct parent. Repeating super will not invoke a method from some other ancestor class. 2. If the subclass does not override a public method of the superclass, you can specify a call to that public method by using the name of the method and an appropriate parameter list. Syntax: methodName(parameter list)
- Constructors (superclass/subclass) o Reminder: Class constructor = A special class method (same name as the class) that executes automatically when an object of that class is created. Constructors are used to guarantee that the instance variables of the class initialize to specific values. A constructor typically serves to initialize instance variables in declaration. o The superclass may have constructors. The subclass can also have its own constructors. When we instantiate a subclass object, this object inherits the instance variables of the superclass, but the subclass object cannot directly access the private instance variables of the superclass. The same is true for the methods of a subclass. That is, the methods of the subclass cannot directly access the private members of the superclass. As a consequence, the constructors of the subclass can (directly) initialize only the instance variables of the subclass. Thus, when a subclass object is instantiated, to initialize the private instance variables it must also automatically execute one of the constructors of the superclass. A call to a constructor of the superclass is specified in the definition of a subclass constructor by using the reserved word super. o Defining constructors of the subclass --> Call to constructor of the superclass. The call to the superclass constructor must be the first statement in the subclass constructor and it must use super. o Once you write a constructor (that requires parameters) in the superclass, you must write constructors for the subclass as well. If not --> program errors. Why? Constructors aren't inherited. - Protected members of a class: o Reminder: As discussed earlier, private members of a class cannot be directly accessed outside the class (only method members of the class can access private members of the class) --> A subclass cannot directly access the private members of the superclass. o The problem: Sometimes it is necessary to give the subclass access to the private members of the superclass. How? If you allow a private member to become public, then anyone can access that member (unsafe direct access) --> not good! o Solution: A superclass could give access to a member to its subclass and still prevent its direct access outside the class, by declaring that member protected. The accessibility of a protected member of a class is somewhere between public and private. A subclass can directly access the protected members of the superclass. o Conclusion: If a subclass needs to access a member of the superclass, and the subclass also needs to prevent direct access of the member outside the class, the member of the superclass can be declared as protected. o Definition: If a method or instance variable is modified by protected (rather than public or private), then it can be accessed by name inside its own class definition, inside any subclass derived from it or in the definition of any class in the same package. o NOTE: The protected modifier provides very weak protection compared to the private modifier, because it allows direct access to any programmer who defines a suitable subclass. Therefore, instance variables should normally NOT be marked protected. - The class Object o In Java, if you define a class and do not use the reserved word extends to derive it from an existing class, then the class you define is automatically considered to be derived from the class Object --> In Java, every class is a subclass of the class Object This also means that the class Object is the superclass of every class in Java. Being a superclass, every public member of the class Object can be overridden and/or can be invoked by every object of any class.
o Every object of every class is of type Object, as well as being of the type of its own class. o NOTE: The class Object is in the package java.lang which is always imported automatically. o The class Object has some methods that every Java class inherits: equals and toString. Every object inherits these methods from some superclass. The superclass could be the class Object, or a class that inherited these methods (ultimately) from the class Object. As noted before, these inherited methods should be overridden with definitions more appropriate to a given class. o NOTE: Some Java library classes assume that every class has its own version of such methods. o Having an Object class enables methods to be written with a parameter of type Object. A parameter of type Object can be replaced by an object of any class whatsoever. Example:
o NOTE: To determine whether a reference variable that points to an object is of a particular class type, Java provides the operator instanceof. o Some explanations: Since the equals method is always inherited from the class Object, methods like the following simply overload it:
However, this method should be overridden, not just overloaded: public
boolean equals(Object otherObject) { The overridden version of equals must meet the following conditions:
public
boolean equals(Object obj){
Programming Samples: Inheritance: Class Rectangle - Class Box //Rectangle
Class: superclass //superclass: default constructor //superclass: alternate constructor public void set(double l, double w) { public double getLength() {
public double getWidth() { public double area() { public double perimeter() { public void print() { public String toString() { public boolean equals(Rectangle r) { //Box
Class: subclass //subclass default constructor //subclass alternate constructor //Method set: will overload same method from superclass
public double getHeight() {
//Method area: will override same method from superclass
public double volume() { //Method print: will override same method from superclass
//Method toString: will override same method from superclass
//Method equals: will overload same method from superclass //Client
program SAMPLE OUTPUT: First box: Length =
0.0; Width = 0.0; Height = 0.0 Inheritance: Class Time - Class ExtendedTime //Class
Time: superclass
//Default constructor
//Alternate constructor with parameters, to set the time
//Method to set the time
//Method to return the hours
//Method to return the minutes
//Method to return the seconds
//Method to print time in military format
//Method to print time in standard format
//Method toString
//Time advanced by one hour.
//Time advanced by one minute.
//Time advanced by one second. When 23:59:59 wrap around to 00:00:00
//Method to compare two times for equality
//Method to compare two times for less than
//Method to copy the time
//Method to return a copy of the time
} //Class
ExtendedTime: subclass
//Default constructor
//Alternate constructor public void setTime(int h, int m, int
s, String z) { public String toString(){ public String getZone(){ public void printTimeMilitary(){
public void printTimeStandard(){
public void copy(ExtendedTime otherTime) { public ExtendedTime getCopy() {
public boolean equals(ExtendedTime otherTime) { //Client
program for Time/ExtendedTime public static void main(String[] args)
{
System.out.print("Initial time t1 (alternate
constructor invoked) - military format: ");
System.out.print("Initial time t2 (default
constructor invoked) - military format: ");
t2.setTime(9, 45, 35);
if (t1.equals(t2))
if (t1.lessThan(t2)) System.out.print("Enter hours, minutes, and seconds (Pacific Standard Time): "); //consider calling a method to do input
validation
z = "PST";
z = "CST";
z = "EST"; t2 = t1.getCopy(); // OR: t2.copy(t1);
System.out.print("New t2 after call to copy -
standard format: "); Base class: Existing class; same
as superclass. Additional
Resources: References: |