CS102 Algorithims and Programming II1 Inheritance Inheritance defines a relationship among classes. A class C2 may inherit from (extend – derive from)

Slides:



Advertisements
Similar presentations
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Advertisements

Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Inheritance and.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.
1 Inheritance in Java CS 3331 Fall Outline  Overloading  Inheritance and object initialization  Subtyping  Overriding  Hiding.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Inheritance. Introduction Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Topic 4 Inheritance.
Inheritance and Access Control CS 162 (Summer 2009)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Lecture 4: Extending Classes. Concept Inheritance: you can create new classes that are built on existing classes. Through the way of inheritance, you.
 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Classes, Interfaces and Packages
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Inheritance ndex.html ndex.htmland “Java.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
BY:- TOPS Technologies
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Java Programming Fifth Edition Chapter 9 Introduction to Inheritance.
Modern Programming Tools And Techniques-I
Chapter 11 Inheritance and Polymorphism
CompSci 230 S Programming Techniques
Inheritance and Polymorphism
COP 3331 Object Oriented Analysis and Design Chapter 5 – Classes and Inheritance Jean Muhammad.
Polymorphism.
Object-Oriented Programming: Polymorphism
Object Oriented Programming
Designing for Inheritance
Overloading and Constructors
Chapter 9 Inheritance and Polymorphism
Object-Oriented Programming: Polymorphism
Review of Object-Oriented Concepts in JAVA
Extending Classes.
Java Programming Language
Java – Inheritance.
Java Programming, Second Edition
Java Inheritance.
Review of Object-Oriented Concepts in JAVA
Chapter 8 Inheritance.
Inheritance.
Inheritance in Java CS 3331 Fall 2009.
Chapter 8 Class Inheritance and Interfaces
Chapter 9 Polymorphism.
Chapter 11 Inheritance and Polymorphism Part 1
Final and Abstract Classes
Presentation transcript:

CS102 Algorithims and Programming II1 Inheritance Inheritance defines a relationship among classes. A class C2 may inherit from (extend – derive from) another class C1. C1parent (super-class) C2child (sub-class) We say that C1 is the parent (super-class) of C2. Or, C2 is the child (sub-class) of C1.

CS102 Algorithims and Programming II2 Inheritance (cont.) Using inheritance mechanism, a sub-class will inherit functionalities of its super-class. Of course, a sub-class may also define its own functionalities. So, a sub-class will have: –its own fields + the fields inherited from its super-class –its own methods + the methods inherited from its super-class. All of the members of a super-class will be inherited by its sub-class, but only certain members will be directly accessible by their names in that sub-class. –public and protected members of a class are accessible by name from the sub-classes of that class. –private members cannot be accessible by name from the sub-classes. –package members are accessible by name from the sub-classes in the same package.

CS102 Algorithims and Programming II3 extends keyword extends clause specifies the super-class of a class. ClassModifiers class SubClassName extends SuperClassName { ClassMemberDeclarations } class C2 extends C1 {... } sub-class super-class (child)(parent) C2 is derived from C1 (C2 is inherited from C1).

CS102 Algorithims and Programming II4 Object class If we do not use an extends clause in a class declaration, the super- class of that declared class is Object class. In Java, every class (except Object class) has a super-class. class C1 {... } is equivalent to class C1 extends Object {... } This means that Object class will be on the top of the class hierarchy. In other words, the class hierarchy in Java is a tree, and its root node is Object class.

CS102 Algorithims and Programming II5 Inheritance (Example) class C1 { public int x=1; public void printX() { System.out.println(“x:”+x); } } class C2 extends C1 { public int y=2; public void printY() { System.out.println(“y:”+y); } public void printBoth() { printX(); printY(); } public void printAddXY() { System.out.println(“x+y:”+(x+y); } } public class Test { public static void main(String[] args) { C2 obj = new C2(); obj.printY(); obj.printBoth(); obj.printX(); obj.printAddXY(); obj.y = 4; obj.x = 3; C1 obj2 = new C1(); obj2.printX(); obj2.x = 5;..... }}

CS102 Algorithims and Programming II6 Constructors of Sub-Classes The initialization of the fields of a sub-class consists of two phases: –The initialization of the inherited fields –The initialization of the fields that are declared in that sub-class. One of the constructors of the super-class must be invoked to initialize the fields inherited from the super-class. –One of the constructors of the super-class must be invoked explicitly; Otherwise the no- argument version of the constructor of the super-class will be automatically invoked. –This invocation must be the first statement of the constructor of the sub-class. (Or the one of the constructors of the sub-class must invoke another version of the constructor of that sub-class).

CS102 Algorithims and Programming II7 Constructors of Sub-Classes (Example) class C1 { private int x; public C1() { x=0; } public C1(int xv) { x=xv; } } class C2 extends C1 { private int y; public C2(int xv, int yv) { super(xv); the constructor of the super-class is explicitly invoked y = yv; } public C2(int yv) { this(1,yv); Another version of the constructor of this class is invoked } public C2() { y = 2; No-argument version of the constructor of the super-class } } is implicitly invoked. super();

CS102 Algorithims and Programming II8 Constructors (cont.) What happens when no constructor is defined for a class?  No-argument constructor will be provided implicitly for that class class C2 extends C1 { // no constructor is defined public C2() { // this constructor is super(); // automatically provided by Java. } If super-class does not have no-argument version of the constructor, a compilation error occurs. If another constructor of the class is present, no-argument version of the constructor will not be provided automatically.

CS102 Algorithims and Programming II9 Order of Initialization Step 1.The fields of the super-class are initialized using default values. 2.One of the constructors of the super-class is executed. 3.The fields of the extended class (sub-class) are initialized using the default values. 4.One of the constructors of the extended class (sub-class) is executed.

CS102 Algorithims and Programming II10 Order of Initialization Step (cont.) class C1 { private int x = 1; // executed first public C1() { x = 2; // executed second } class C2 extends C1 { private int y = 3; // executed third public C2() { super(); y = 4 ; // executed fourth }

CS102 Algorithims and Programming II11 Class Hierarchies Multiple classes can be derived from a single parent. Inheritance relations develop into a class hierarchy. C1 C2 C3 C4 C5 C6 C7 Parent classes should carry most general properties. Child classes should carry most specific properties.

CS102 Algorithims and Programming II12 Object Class All classes in Java are derived from Object class. If a class definition does not use extends clause, that class is derived from Object class. class C1 {... } is equivalent to class C1 extends Object {... } So, all clause in Java, directly or indirectly derived from Object class.

CS102 Algorithims and Programming II13 Object Class class C1 {... } class C2 extends C1 {... } class C3 extends C1 {... } class C4 extends C2 {... } class C5 extends C2 {... } class C6 {... } class C7 extends C6 {... } Object C1C6 C2 C3C7 C4 C5

CS102 Algorithims and Programming II14 Inheritance and References The data type of a variable can be: –a primitive data type, or –a reference type (which will hold a reference to an object). So, a variable of reference type holds a reference to an object. class C1 {... } // in some other place C1 x; What can be the class of the object which is referred by the variable x? A variable of reference type can refer an object of its declared class, or to an object of any subclass of its declared subclass. –This means that x can store a reference to an object of C1 or an object of any subclass of C1 (its siblings).

CS102 Algorithims and Programming II15 Inheritance and References (cont.) class C1 {... } class C2 extends C1 {... } class C3 {... } // in some other place C1 o1 = new C1();C2 o2 = new C2();C3 o3 = new C3(); o1 = o2; Automatically saved (Widening Conversion) o2 = (C2) o1; We need explicit type casting (Narrowing Conversion) if o1 holds C2 object, this is okay; But, if o1 holds C1 object  run-time error o1 = o3; ILLEGAL (There is no inheritance relation between C1 and C3) o1 = (C1) o3; ILLEGAL (There is no inheritance relation between C1 and C3)

CS102 Algorithims and Programming II16 Inheritance and References (cont.) Assigning a predecessor reference to an ancestor reference is considered to be a widening conversion, and it can be performed by simple assignment. Assigning an ancestor reference to a predecessor reference is considered to be a narrowing conversion, and it must be done with an explicit type cast operation. –If that ancestor reference does not points to a predecessor object  run-time error Since Object class is the ancestor of all classes in Java, we can store any type of reference in an Object reference variable;

CS102 Algorithims and Programming II17 Inheritance and References (cont.) class C1 {... } class C2 extends C1 {... } // in some other place C1 o1 = new C1();C2 o2 = new C2(); Object o3; o1 = o2; Automatically saved (Widening Conversion) o2 = (C2) o1; We need explicit type casting (Narrowing Conversion) This is okay, because o1 holds an C2 object. o3 = o1; Automatically saved (Widening Conversion) o3 = o2; Automatically saved (Widening Conversion)

CS102 Algorithims and Programming II18 Inheritance and References (cont.) So, a variable of reference type holds a reference to an object. A variable of reference type may hold references to objects of different classes. Subtype Rules determine what kind of references (references to the objects of which classes) can be held by a variable of reference type. The class of the object referred to by a reference variable cannot always be determined at compile time.  it can be determined only at run time.

CS102 Algorithims and Programming II19 Subtypes There is another view classes and inheritance.  types and subtype relation Each class defines a type. All the instances of the class constitute the set of the legitimate values of that type. Every instance of a subclass is also an instance of its superclass,  the type type defined by the subclass is a subset of the type defined by its superclass. In other words, the type defined by the subclass is a subtype of the type defined by its superclass.

CS102 Algorithims and Programming II20 Subtype and Supertype Definition of Subtype: Type T 1 is a subtype of type T 2 if every legitimate value of T 1 is also a legitimate value of T 2. We also call that, T 2 is the supertype of T 1. The inheritance relation among classes is a subtype relation. class C1 {... } class C2 extends C1 {... } class C3 extends C2 {... } class C4 {... } –C1 is a subtype of Object. –C2 is a subtype of C1. C2 is a subtype of Object. –C3 is a subtype of C2. C3 is a subtype of C1. C3 is a subtype of Object. –C4 is a subtype of Object.

CS102 Algorithims and Programming II21 Subtype and Supertype (cont.) Rule of Subtypes: A value of a subtype can appear wherever a value of its supertype is expected.  An instance of a subclass can appear wherever an instance of its superclass is expected. Conversion of Reference Types: –The conversion of reference type is governed by the subtype relation. –The conversion of a subtype to one of its supertypes is called widening conversion. –The conversion of a supertype to one of its subtypes is called narrowing conversion.

CS102 Algorithims and Programming II22 Conversion of Types So, type T 1 can be converted into type T 2, if they is a subtype relation between T 1 and T 2 (this conversion can be a widening conversion or a narrowing condition – explicit type casting is required for narrowing conversion). Widening of a reference type is always allowed and is carried out implicitly whenever necessary. Narrowing of a reference type requires an explicit type casting. –Narrowing is not always safe, and may result in run-time exceptions. There is a difference between conversions of primitive types and reference types: –During the conversion of a primitive type, the representation of the value being converted is changed. –The conversion of an object reference does not affect the representation of the object. The identity of object and state remain same.

CS102 Algorithims and Programming II23 Polymorphism Rule of Assignment: The type of the expression at the right-side of an assignment must be the same type as or a subtype of the type of the variable at the left-hand side of the assignment. class Student {... } class Undergraduate extends Student {... } class Graduate extends Student {... } Student student1, student2; student1 = new Undergraduate(); // polymorphic assignment student2 = new Graduate(); // polymorphic assignment

CS102 Algorithims and Programming II24 Polymorphism (cont.) Graduate student3; Although student2 holds a Graduate object, the following statement will be illegal. student3 = student2;  compilation error But, the following will be okay: student3 = (Graduate) student2; student3 = (Graduate) student1;  runtime error because student1 holds an Undergraduate object.

CS102 Algorithims and Programming II25 Downcasting Casting a variable to a subtype of its declared type is called downcasting. For example, explicit type casting of the variable student2 whose declared type is Student is downcasting. Graduate student3; student3 = (Graduate) student2; Java allows explicit type casting of any reference type T 1 to any reference type T 2 which holds a subclass relation with T 1 at compile time. The validity of an explicit type casting is always checked at run time. If the cast is invalid, a ClassCastException will be thrown. In our example, a run-time check will be performed to determine whether student2 holds a reference to an object that is an instance of Graduate or its subclasses. If it is not, a ClassCastException will be thrown.

CS102 Algorithims and Programming II26 Proper Ways of Downcasting Use instanceof operator before downcasting: expression instanceof Type returns true if expression is an instance of Type (or its subtype). if (student1 instanceof Graduate) { Graduate gradStudent = (Graduate) student1;... } else { // student1 is not a graduate student... }

CS102 Algorithims and Programming II27 Proper Ways of Downcasting (cont.) Catch ClassCastException exception: try { Graduate gradStudent = (Graduate) student1;... } catch (ClassCastException e) { // student1 is not a graduate student... }

CS102 Algorithims and Programming II28 Is Downcasting is Needed? If Graduate class defines a method getResearchTopic() and this method is not defined in Student class, the following code will give a compilation error (although s1 holds a Graduate object). Student s1 = new Graduate(); s1.getResearchTopic();  compilation error. So, we have to downcast s1 to Graduate, before we invoke the method. Student s1 = new Graduate(); Graduate gs = (Graduate) s1; gs.getResearchTopic();

CS102 Algorithims and Programming II29 Array Types Arrays are also objects. The subtype relationship among array types are defined as follows: –Each array type is a subtype of Object –If the type T 2 is a subtype of T 1, then T 2 [] is a subtype of T 1 []. Object int[] double[] C1C1[] C2 C2[]

CS102 Algorithims and Programming II30 Overriding Methods The introduction of an instance method in a subclass that has the same name, signature, and return type of a method in the superclass is called as overriding. The implementation of the method in the subclass replaces the implementation of the method in the superclass. Overriding a method another method of different signature or return type is not allowed in Java (in C++, this legal). For this case, Java will assume that it is an overloading operation.

CS102 Algorithims and Programming II31 Overriding (cont.) class C1 { public void m() {... } } class C2 extends C1 { public void m() {... } } C1 o1 = new C1(); C2 o2 = new C2(); o1.m();  invoke m() in C1 o2.m();  invoke m() in C2 C1 o = new C2(); o.m();  which m() is invoked?  m() in C2 is invoked

CS102 Algorithims and Programming II32 Polymorphic Method Invocation Which implementation of an overridden method will be invoked depends on the actual class of the object referenced by the variable at run time, not the declared type of the variable. This is known as polymorphic method invocation. In the polymorphic method invocation, the implementation of a method is dynamically bound to an invocation at runtime. Dynamic binding for a polymorphic method invocation x.m() works as follows: 1.currentClass is the class of the object referenced by x. 2.if method m() is implemented in currentClass then the implementation of m() in currentClass is invoked else set currentClass to the superclass of currentClass, and repeat the step 2.

CS102 Algorithims and Programming II33 Polymorphic Method Invocation -- Example class C { public void m() {... } } class C1 extends C { public void m() {... } } class C2 extends C1 {... } class C3 extends C {... } C x; x = new C(); x.m();  m() in C is invoked. x = new C1(); x.m();  m() in C1 is invoked. x = new C2(); x.m();  m() in C1 is invoked. x = new C3(); x.m();  m() in C is invoked.

CS102 Algorithims and Programming II34 Final Methods A method that is declared using final keyword cannot be overridden in a subclass. Final methods are useful in preventing a subclass from accidentally overriding methods that should not be overridden.

CS102 Algorithims and Programming II35 Invoking Overridden Methods class C1 { public void m() {... } } class C2 extends C1 { public void m() { super.m();  will invoke m() in C1 } The super reference can be used to explicitly invoke any method of a parent class. We can use the super reference to call the parent’s version of an overridden method.

CS102 Algorithims and Programming II36 A Strange Overriding Example class C1 { int x=1; static int y=2; void m1() { System.out.println("C1-m1"); } static void m2() { System.out.println("C1-m2"); } } class C2 extends C1 { int x=5; static double y=6; void m1() { System.out.println("C2-m1-noarg"); } void m1(int a) { System.out.println("C2-m1-1arg"); } static void m2() { System.out.println("C2-m2-noarg"); } static void m2(int a) { System.out.println("C2-m2-1arg"); } void printParentProperties() { System.out.println("super.x:"+super.x); System.out.println("super.y:"+super.y); super.m1(); super.m2(); } }

CS102 Algorithims and Programming II37 A Strange Overriding Example (cont.) // in some other place C2 c2obj = new C2(); c2obj.m1(); c2obj.m1(1); c2obj.m2(); c2obj.m2(1); C1.m2(); C2.m2(); C2.m2(1); c2obj.printParentProperties();

CS102 Algorithims and Programming II38 Hiding and Overriding When a subclass declares a field (an instance variable), a static variable or a static method that is already declared in its superclass, it is hidden (not overridden). Overriding and hiding are different concepts: –An instance method can only be overridden. An instance method can be only overridden by a method of same signature and same return type. –An instance variable, a static variable and a static method can only be hidden. When an overridden method is invoked, the implementation that will be executed is chosen at run time (dynamically bound). When a hidden method or variable is invoked or accessed, the copy that will be used is determined at compile time (statically bound).

CS102 Algorithims and Programming II39 Hiding and Overriding -- Example class C1 { int x=1;static int y=2; void m1() { System.out.println("C1-m1"); } static void m2() { System.out.println("C1-m2"); } } class C2 extends C1 { int x=5;static int y=6; void m1() { System.out.println("C2-m1"); } static void m2() { System.out.println("C2-m2"); } } C2 c2obj = new C2(); C1 c1obj = c2obj; System.out.println("c2obj: x: "+c2obj.x+" y: "+c2obj.y);  x:5 y:6 System.out.println("c1obj: x: "+c1obj.x+" y: "+c1obj.y);  x:1 y:2 c2obj.m1();  C2-m1 c1obj.m1();  C2-m1 c2obj.m2();  C2-m2 c1obj.m2();  C1-m2

CS102 Algorithims and Programming II40 Hiding and Overriding – Example2 class C1 { int x=1;static int y=2; void m1() { System.out.println("C1-m1"); } static void m2() { System.out.println("C1-m2"); } } class C2 extends C1 { double x=5;static double y=6;  variables can be hidden with variables with different types void m1(int a) { System.out.println("C2-m1"); }  different signature will cause to static void m2(int a) { System.out.println("C2-m2"); } overloading. } C2 c2obj = new C2(); C1 c1obj = c2obj; System.out.println("c2obj: x: "+c2obj.x+" y: "+c2obj.y);  x:5.0 y:6.0 System.out.println("c1obj: x: "+c1obj.x+" y: "+c1obj.y);  x:1 y:2 c2obj.m1();  C1-m1 Since m1 is overloaded, no-argument version of m1 is called (declared in C1) c1obj.m1();  C1-m1 Since m1 is overloaded, no-argument version of m1 is called (declared in C1) c2obj.m2();  C1-m2 Since m2 is overloaded, no-argument version of m2 is called (declared in C1) c1obj.m2();  C1-m2 c2obj.m1(1);  C2-m1 c2obj.m2(1);  C2-m2 c1obj.m1(1);  compilation error – because C1 does not one argument version of m1 c1obj.m2(1);  compilation error – because C1 does not one argument version of m2

CS102 Algorithims and Programming II41 Hiding and Overriding – Example3 class C1 { void m1() { System.out.println("C1-m1"); } static void m2() { System.out.println("C1-m2"); } } class C2 extends C1 { // Java will give compilation errors for two following method declarations, // because they are trying to override (hide) using different return types int m1() { System.out.println("C2-m1"); return 0;} static int m2() { System.out.println("C2-m2"); return 0; } }

CS102 Algorithims and Programming II42 Abstract Classes and Methods An abstract class represents a generic concept in a class hierarchy. An abstract class cannot be instantiated. This means that we cannot create an object of an abstract class. An abstract class should be declared using abstract keyword and normally contains one or more abstract methods. An abstract method is an instance method without an implementation. –A static method cannot be an abstract method. abstract class A1 {  an abstract class abstract void m1();  an abstract method }

CS102 Algorithims and Programming II43 Abstract Class An abstract class contains abstract methods, and it may also contain normal (non-abstract) properties. Children (subclasses) of an abstract class are expected to define implementations for the abstract methods. If a subclass of an abstract class does not define implementations of all abstract methods of its superclass, it must be also an abstract class (and it must be defined using abstract keyword). An abstract class can be used same as other classes except that it cannot be instantiated.

CS102 Algorithims and Programming II44 Abstract Class (cont.) abstract class A1 { abstract void m1(); abstract String m2(); } class C1 extends A1 { void m1() { System.out.println(“C1-m1”); } String m2() { return “C1-m2”; } } abstract C2 extends A1 { void m1() { System.out.println(“C2-m1”); } }  C2 must be abstract, because it does not implement the abstract method m2.

CS102 Algorithims and Programming II45 Abstract Method An abstract method is an instance method without an implementation. A static method cannot be abstract. –a static method can be invoked by just using the name of the class (without creation an object). –If a static method can be an abstract method, this means that a method without an implementation can be invoked (which this is impossible). An abstract method cannot be declared using final keyword, because its implementation must be given by children classes. –Remember that a method declared using final keyword cannot be overridden.

CS102 Algorithims and Programming II46 Abstract Classes (cont.) Abstract classes (and abstract methods) can be used as tools to organize a software system. In an abstract class, we decide which methods will be written without actually implementing. By defining an abstract method (we only define its return type and its signature), we decide how we are going to communicate with that method. Later, the subclasses of that abstract class give the implementations of those abstract methods.

CS102 Algorithims and Programming II47 Interfaces In Java, interfaces declare methods but they do not provide any implementation. A Java interface is a collection of abstract methods and constants. interface interfacename { - constant declarations - abstract methods } An interface looks like a class, but it is not a class. It is not in the class hierarchy.

CS102 Algorithims and Programming II48 Interfaces interface I1 { Although we do not write here, it is assumed that CONST1 is declared as a constant (with int CONST1=5; keywords public, final and static ) void m1() ; Although we do not write here, it is assumed } that m1 is declared with keywords public and abstract.

CS102 Algorithims and Programming II49 Implementing Interfaces Interfaces are intended to capture the common characteristics and behavior of the classes that implement the interfaces. A class that implements an interface must provide implementations for all of the methods in that interface. A class can implement an interface as follows: class classname implements interfacename {.. implementations of all methods in the interface } must be provided here.

CS102 Algorithims and Programming II50 Implementing Interfaces - Example class C1 implements I1 {.. implementations of all methods in the interface I1. must be provided here.. } All constants in I1 can be accessible in C1 as its own variables.

CS102 Algorithims and Programming II51 Implementing Interfaces (cont.) An interface can be implemented by multiple classes. Each implementing class can provide their own unique versions of the method definitions. interface I1 { void m1() ; } class C1 implements I1 { public void m1() { System.out.println(“Implementation in C1”); } } class C2 implements I1 { public void m1() { System.out.println(“Implementation in C2”); } }

CS102 Algorithims and Programming II52 Single Inheritance versus Multiple Inheritance Single inheritance means that each subclass has exactly one superclass, and that subclass can only inherit from its single superclass. Multiple inheritance means that each subclass can have more than one superclass, and that subclass can inherit from its all superclasses. C1C1 C2 C3 C2C4 single inheritancemultiple inheritance Java supports only single inheritance among classes. (C++ support multiple inheritance.). Multiple inheritance is difficult to use.

CS102 Algorithims and Programming II53 Weak Form of Multiple Inheritance (!) Using interfaces, Java supports somehow a weak form of multiple inheritance (it is not actual multiple inheritance). In Java, a class may implement more than one interface, and this can be seen as a weak form of multiple inheritance (but it is not multiple inheritance). class classname implements interface1,…, interfacen {.. implementations of all methods in the all interfaces } must be provided here.

CS102 Algorithims and Programming II54 Implementing More Than One Interface interface I1 { void m1(); } interface I2 { void m2() ; C must implement all methods in I1 and I2. void m3() ; } class C implements I1, I2 { public void m1() { System.out.println(“C-m1”); } public void m2() { System.out.println(“C-m2”); } public void m3() { System.out.println(“C-m3”); } }

CS102 Algorithims and Programming II55 Resolving Name Conflicts Among Interfaces Since a class may implement more than one interface, the names in those interfaces may collide. To solve name collisions, Java use a simple mechanism. Two methods that have the same name will be treated as follows in Java: –If they are different signature, they are considered to be overloaded. –If they have the same signature and the same return type, they are considered to be the same method and they collapse into one. –If they have the same signature and the different return types, a compilation error will occur.

CS102 Algorithims and Programming II56 Resolving Name Conflicts Among Interfaces interface I1 { void m1(); void m2(); void m3(); } interface I2 { void m1(int a); There will be a compilation error for m3. void m2(); int m3(); } class C implements I1, I2 { public void m1() { … } // implementation of m1 in I1 public void m1(int x) { … } // implementation of m1 in I2 public void m2() { … } // implementation of m1 in I1 and I2 }

CS102 Algorithims and Programming II57 Inheritance Relation Among Interfaces Same as classes, interfaces can hold inheritance relation among them. interface I2 extends I1 { … } Now, I2 contains all abstract methods of I1 plus its own abstract methods. The classes implementing I2 must implement all methods in I1 and I2.

CS102 Algorithims and Programming II58 Interfaces as Data Types Interfaces (same as classes) can be used as data types. Different from classes: We cannot create an instance of an interface. interface I1 { … } class C1 implements I1 { … } class C2 extends C1 { … } // a variable can be declared as type I1 I1 x; A variable declared as I1, can store objects of C1 and C2.

CS102 Algorithims and Programming II59 Subtypes Each interface also defines a data type. The interface relation among interfaces, and the implementation relation between a class and interfaces create subtype relations. Complete subtype relations in Java as follows: –If class C 1 extends class C 2, then C 1 is a subtype of C 2. –If interface I 1 extends interface I 2, then I 1 is a subtype of I 2. –If class C implements interface I, then C is a subtype of I. –For every interface I, I is a subtype of Object. –For every type T (reference or primitive), T[] (array type of T ) is a subtype of Object. –If type T 1 is a subtype of T 2, then T 1 [] is a subtype of T 2 [].

CS102 Algorithims and Programming II60 Case Study - Employee In this case study, we will design a class hierarchy for the employees of a firm using inheritance. In this design, we will see how to create classes and how to set up inheritance relations among these classes. We will use abstract classes. We will use polymorphic references, and polymorphic method invocation.

CS102 Algorithims and Programming II61 Case Study – Problem Definition A firm has employees. An employee can be a volunteer or a paid employee. Each employee has a name and an address. We should be able to get a string representation of an employee. Each employee should be associated with an earning method to evaluate his/her monthly earnings (whether 0 or not, this method must be available). A volunteer is not paid (his/her earnings is zero). A paid employee has to have a social security number. A paid employee can be an executive, a monthly-employee, or a hourly-employee. A monthly-employee has a monthly salary. An executive has a monthly salary and a bonus for that month. A hourly-employee earnings depends on how many hours he/she worked on that month (there is a wage per hour for him/her).

CS102 Algorithims and Programming II62 A Class Hierarchy Employee VolunteerPaidEmployee Executive MonthlyEmployee HourlyEmployee The inheritance relations among classes. Now let us look at the details of each class.

CS102 Algorithims and Programming II63 Class Details Employee class: –This class has to have two fields: name and address –Its constructor must initialize these fields. –Its toString should return a string representation of these fields. –It should enforce that its subclasses have to have an earnings method.This means that it has to have an abstract earnings method. This class must be an abstract class. Volunteer class: –This class will be a sub-class of Employee class. –Since we do not need another information about a volunteer, we do not need to define new fields in this class. –Its toString should return a string representation indicating that this employee is a volunteer. –Its earnings method should return 0 since a volunteer is not paid. –Since earnings method is implemented in this class, it can be a normal class.

CS102 Algorithims and Programming II64 Class Details (cont.) PaidEmployee class: –This class will be a sub-class of Employee class. –Since we need a social security number for a paid employee, this class should define a new field: socialSecurityNumber. –Its toString should return a string representation of these three fields.. –Since this method does not implement earnings method, it should be abstract. Executive class: –This class will be a sub-class of PaidEmployee class. –Since we need a monthly salary and a bonus for an executive, this class should define the fields: salary and bonus. –Its toString should return a string representation indicating that this employee is an executive. –Its earnings method should return the summation of salary and bonus. –Since we may change the bonus of an executive, this class should include setBonus method. –Since earnings method is implemented in this class, it can be a normal class.

CS102 Algorithims and Programming II65 Class Details (cont.) MonthlyEmployee class: –This class will be a sub-class of PaidEmployee class. –Since we need a monthly salary for a monthly-employee, this class should define the field: salary. –Its toString should return a string representation indicating that this employee is a monthly-employee. –Its earnings method should return the salary. –Since earnings method is implemented in this class, it can be a normal class. HourlyEmployee class: –This class will be a sub-class of PaidEmployee class. –This class should define the fields: wage and hours. –Its toString should return a string representation indicating that this employee is a hourly-employee. –Its earnings method should return the multiplication of wage and hours. –Since we may add hours for a hourly-employee, this class should include addHours method. –Since earnings method is implemented in this class, it can be a normal class.

CS102 Algorithims and Programming II66 Other Classes Personnel class: –This class will declare an Employee array to hold all employees of a firm. –It should also include payday method to print paychecks for employees. EmployeeTest class: –A driver class. –It will create a Personnel object, and will call payday method with this object.

CS102 Algorithims and Programming II67 Employee Class public abstract class Employee { protected String eName; protected String eAddress; // Set up an employee using the specified information public Employee(String name, String address) { eName=name; eAddress=address; } // Return a string containg the basic employee information public String toString() { return ( "Name: " + eName + "\n" + "Address: " + eAddress ) ; } // All subclasses of Employee class must define earnings method public abstract double earnings() ; }

CS102 Algorithims and Programming II68 Volunteer Class public class Volunteer extends Employee { // Set up a volunteer using the specified information public Volunteer(String name, String address) { super(name,address); } // Return a string containing the paid employee information public String toString() { return ( "Volunteer\n" + super.toString()); } // Volunteers are not paid public double earnings() { return 0.0; } }

CS102 Algorithims and Programming II69 PaidEmployee Class public abstract class PaidEmployee extends Employee { protected String socialSecurityNumber; // Set up a paid employee using the specified information public PaidEmployee(String name, String address, String ssn) { super(name,address); socialSecurityNumber=ssn; } // Return a string containing the paid employee information public String toString() { return ( super.toString() + "\nSSN: " + socialSecurityNumber) ; } }

CS102 Algorithims and Programming II70 Executive Class public class Executive extends PaidEmployee { private double salary; private double bonus; // Set up an executive using the specified information public Executive(String name, String address, String ssn, double salary) { super(name,address,ssn); this.salary=salary; bonus=0.0; } // Set up the bonus for the executive public void setBonus(double bonus) { this.bonus=bonus; } // Return a string containing the Executive information public String toString() { return ( "Executive\n" + super.toString() + "\nSalary: " + salary + "\nBonus: " + bonus); } // Executives earn a monthly salary plus a bonus public double earnings() { return salary+bonus; } }

CS102 Algorithims and Programming II71 MonthlyEmployee Class public class MonthlyEmployee extends PaidEmployee { private double salary; // Set up a monthly employee using the specified information public MonthlyEmployee(String name, String address, String ssn, double salary) { super(name,address,ssn); this.salary=salary; } // Return a string containing the monthly employee information public String toString() { return ( "Monthly Employee\n" + super.toString() + "\nSalary: " + salary ); } // Monthly employees earn a monthly salary public double earnings() { return salary; } }

CS102 Algorithims and Programming II72 HourlyEmployee Class public class HourlyEmployee extends PaidEmployee { private double wage; // wage per hour private int hours; // hours worked for the month // Set up a hourly employee using the specified information public HourlyEmployee(String name,String address,String ssn,double wage){ super(name,address,ssn); this.wage=wage; hours=0; } // Add hours public void addHours(int hours) { this.hours += hours; } // Return a string containing the hourly employee information public String toString() { return ( "Hourly Employee\n" + super.toString() + "\nWage Per Hour: " + wage + "\nHours Worked: " + hours); } // Get hourly employee's earnings public double earnings() { return wage*hours; } }

CS102 Algorithims and Programming II73 Personnel Class public class Personnel { Employee[] employeeList; // Holds polymorphic references, it can hold objects of sublasses of Employee // Set up the employee list public Personnel() { employeeList = new Employee[5]; employeeList[0] = new Volunteer("Sam Clark","123 Alafaya Trail"); employeeList[1] = new Executive("Bill Brown","124 Alafaya Trail"," ",7500); employeeList[2] = new MonthlyEmployee("John Goodman","125 Alafaya Trail"," ",5000); employeeList[3] = new MonthlyEmployee("Jill Woody","126 Alafaya Trail"," ",4000); employeeList[4] = new HourlyEmployee("Tom Jones","127 Alafaya Trail"," ",9.50); ((Executive)employeeList[1]).setBonus(1200); // Downcasting ((HourlyEmployee)employeeList[4]).addHours(150); ((HourlyEmployee)employeeList[4]).addHours(60); }

CS102 Algorithims and Programming II74 Personnel Class (cont.) // Pays all employees public void payday() { double amount; for (int i=0; i<employeeList.length; i++) { System.out.println(employeeList[i]); amount=employeeList[i].earnings(); // polymorphic method invocation if (amount==0.0) System.out.println("Thanks!"); else System.out.println("Paid: " + amount); System.out.println(" "); } }

CS102 Algorithims and Programming II75 EmployeeTest Class public class EmployeeTest { // Creates the personnel of a firm and pays them public static void main (String[] args) { Personnel staff = new Personnel(); staff.payday(); } }

CS102 Algorithims and Programming II76 Output of The Program