SlideShare ist ein Scribd-Unternehmen logo
1 von 64
Inheritance and Class Hierarchies

Based on Koffmann and Wolfgang
Chapter Outline
• Inheritance and how it facilitates code reuse
• How does Java find the “right” method to execute?
• (When more than one has the same name ...)
• Defining and using abstract classes
• Class Object: its methods and how to override them
• How to “clone” an object
• The difference between:
• A true clone (deep copy) and
• A shallow copy
Chapter 3: Inheritance and Class Hierarchies

2
Chapter Outline (2)
• Why Java does not implement multiple inheritance
• Get some of the advantages of multiple inheritance:
• Interfaces
• Delegation
• Sample class hierarchy: drawable shapes
• An object factory and how to use it
• Creating packages
• Code visibility

Chapter 3: Inheritance and Class Hierarchies

3
Inheritance and Class Hierarchies
• Object-oriented programming (OOP) is popular because:
• It enables reuse of previous code saved as classes
• All Java classes are arranged in a hierarchy
• Object is the superclass of all Java classes
• Inheritance and hierarchical organization capture idea:
• One thing is a refinement or extension of another

Chapter 3: Inheritance and Class Hierarchies

4
Inheritance and Class Hierarchies (2)
superclass

subclass

Chapter 3: Inheritance and Class Hierarchies

5
Is-a Versus Has-a Relationships
• Confusing has-a and is-a leads to misusing inheritance
• Model a has-a relationship with an attribute (variable)
public class C { ... private B part; ...}
• Model an is-a relationship with inheritance
• If every C is-a B then model C as a subclass of B
• Show this: in C include extends B:
public class C extends B { ... }

Chapter 3: Inheritance and Class Hierarchies

6
A Superclass and a Subclass
• Consider two classes: Computer and Laptop
• A laptop is a kind of computer: therefore a subclass
methods of Computer
and all subclasses

additional Methods for
class Laptop
(and its subclasses)

variables of Computer
and all subclasses

additional variables for
class Laptop
(and its subclasses)

Chapter 3: Inheritance and Class Hierarchies

7
Illustrating Has-a with Computer
public class Computer {
private Memory mem;
...
}

A Computer has only one Memory

But neither is-a the other

public class Memory {
private int size;
private int speed;
private String kind;
...
}
Chapter 3: Inheritance and Class Hierarchies

8
Initializing Data Fields in a Subclass
• What about data fields of a superclass?
• Initialize them by invoking a superclass constructor
with the appropriate parameters
• If the subclass constructor skips calling the superclass ...
• Java automatically calls the no-parameter one

• Point: Insure superclass fields initialized before
subclass starts to initialize its part of the object
Chapter 3: Inheritance and Class Hierarchies

9
Example of Initializing Subclass Data
public class Computer {
private String manufacturer; ...
public Computer (String manufacturer, ...) {
this.manufacturer = manufacturer; ...
}
}
public class Laptop extends Computer {
private double weight; ...
public Laptop (String manufacturer, ...,
double weight, ...) {
super(manufacturer, ...);
this.weight = weight;
}
}
Chapter 3: Inheritance and Class Hierarchies

10
Protected Visibility for Superclass Data
• private data are not accessible to subclasses!
• protected data fields accessible in subclasses
(Technically, accessible in same package)
• Subclasses often written by others, and
• Subclasses should avoid relying on superclass details

• So ... in general, private is better

Chapter 3: Inheritance and Class Hierarchies

11
Method Overriding
• If subclass has a method of a superclass (same signature),
that method overrides the superclass method:
public class A { ...
public int M (float f, String s) { bodyA }
}
public class B extends A { ...
public int M (float f, String s) { bodyB }
}
• If we call M on an instance of B (or subclass of B), bodyB runs
• In B we can access bodyA with: super.M(...)
• The subclass M must have same return type as superclass M
Chapter 3: Inheritance and Class Hierarchies

12
Method Overloading
• Method overloading: multiple methods ...
• With the same name
• But different signatures
• In the same class
• Constructors are often overloaded
• Example:
• MyClass (int inputA, int inputB)
• MyClass (float inputA, float inputB)
Chapter 3: Inheritance and Class Hierarchies

13
Example of Overloaded Constructors
public class Laptop extends Computer {
private double weight; ...
public Laptop (String manufacturer,
String processor, ...,
double weight, ...) {
super(manufacturer, processor, ...);
this.weight = weight;
}
public Laptop (String manufacturer, ...,
double weight, ...) {
this(manufacturer, “Pentium”, ...,
weight, ...);
}
}
Chapter 3: Inheritance and Class Hierarchies

14
Overloading Example From Java Library
ArrayList has two remove methods:
remove (int position)
• Removes object that is at a specified place in the list
remove (Object obj)
• Removes a specified object from the list

It also has two add methods:
add
•
add
•

(Element e)
Adds new object to the end of the list
(int index, Element e)
Adds new object at a specified place in the list
Chapter 3: Inheritance and Class Hierarchies

15
Polymorphism
• Variable of superclass type can refer to object of subclass type
• Polymorphism means “many forms” or “many shapes”
• Polymorphism lets the JVM determine at run time which
method to invoke
• At compile time:
• Java compiler cannot determine exact type of the object
• But it is known at run time
• Compiler knows enough for safety: the attributes of the type
• Subclasses guaranteed to obey

Chapter 3: Inheritance and Class Hierarchies

16
Interfaces vs Abstract Classes vs Concrete Classes
• A Java interface can declare methods
• But cannot implement them
• Methods of an interface are called abstract methods
• An abstract class can have:
• Abstract methods (no body)
• Concrete methods (with body)
• Data fields
• Unlike a concrete class, an abstract class ...
• Cannot be instantiated
• Can declare abstract methods
• Which must be implemented in all concrete subclasses
Chapter 3: Inheritance and Class Hierarchies

17
Abstract Classes and Interfaces
• Abstract classes and interfaces cannot be instantiated
• An abstract class can have constructors!
• Purpose: initialize data fields when a subclass object
is created
• Subclass uses super(…) to call the constructor
• An abstract class may implement an interface
• But need not define all methods of the interface
• Implementation of them is left to subclasses
Chapter 3: Inheritance and Class Hierarchies

18
Example of an Abstract Class
public abstract class Food {
public final String name;
private double calories;
public double getCalories () {
return calories;
}
protected Food (String name, double calories) {
this.name
= name;
this.calories = calories;
}
public abstract double percentProtein();
public abstract double percentFat();
public abstract double percentCarbs();
}
Chapter 3: Inheritance and Class Hierarchies

19
Example of a Concrete Subclass
public class Meat extends Food {
private final double protCal; ...;
public Meat (String name, double protCal,
double fatCal double carbCal) {
super(name, protCal+fatCal+carbCal);
this.protCal = protCal;
...;
}
public double percentProtein () {
return 100.0 * (protCal / getCalories());
}
...;
}
Chapter 3: Inheritance and Class Hierarchies

20
Example: Number and the Wrapper Classes
Declares what the
(concrete)
subclasses have in
common

Chapter 3: Inheritance and Class Hierarchies

21
Inheriting from Interfaces vs Classes
• A class can extend 0 or 1 superclass
• Called single inheritance
• An interface cannot extend a class at all
• (Because it is not a class)
• A class or interface can implement 0 or more
interfaces
• Called multiple inheritance

Chapter 3: Inheritance and Class Hierarchies

22
Summary of Features of Actual Classes,
Abstract Classes, and Interfaces

Chapter 3: Inheritance and Class Hierarchies

23
Class Object
• Object is the root of the class hierarchy
• Every class has Object as a superclass
• All classes inherit the methods of Object
• But may override them

Chapter 3: Inheritance and Class Hierarchies

24
The Method toString
• You should always override toString method if you
want to print object state
• If you do not override it:
• Object.toString will return a String
• Just not the String you want!
Example: ArrayBasedPD@ef08879
... The name of the class, @, instance’s hash code

Chapter 3: Inheritance and Class Hierarchies

25
Operations Determined by Type of
Reference Variable
• Variable can refer to object whose type is a subclass of the
variable’s declared type
• Type of the variable determines what operations are legal
• Java is strongly typed Object athing = new Integer(25);
• Compiler always verifies that variable’s type includes the
class of every expression assigned to the variable

Chapter 3: Inheritance and Class Hierarchies

26
Casting in a Class Hierarchy
• Casting obtains a reference of different, but matching, type
• Casting does not change the object!
• It creates an anonymous reference to the object
Integer aNum = (Integer)aThing;
• Downcast:
• Cast superclass type to subclass type
• Checks at run time to make sure it’s ok
• If not ok, throws ClassCastException
Chapter 3: Inheritance and Class Hierarchies

27
Casting in a Class Hierarchy (2)
• instanceof can guard against ClassCastException
Object obj = ...;
if (obj instanceof Integer) {
Integer i = (Integer)obj;
int val = i.intValue();
...;
} else {
...
}
Chapter 3: Inheritance and Class Hierarchies

28
Downcasting From an Interface Type
Collection c = new ArrayList();
...;
... ((ArrayList)c).get(3) ...

Chapter 3: Inheritance and Class Hierarchies

29
Polymorphism Reduces Need For Type Tests
// Non OO style:
if (stuff[i] instanceof Integer)
sum += ((Integer) stuff[i]).doubleValue();
else if (stuff[i] instanceof Double)
sum += ((Double) stuff[i]).doubleValue();
...
// OO style:
sum += stuff[i].doubleValue();

Chapter 3: Inheritance and Class Hierarchies

30
Polymorphism and Type Tests (2)
• Polymorphic code style is more extensible
• Works automatically with new subclasses
• Polymorphic code is more efficient
• System does one indirect branch vs many tests
• So ... uses of instanceof are suspect

Chapter 3: Inheritance and Class Hierarchies

31
Java 5.0 Reduces Explicit Conversions
• Java 1.4 and earlier:
Character ch = new Character(‘x’);
char nextCh = ch.charValue();

• Java 5.0:
Character ch = ‘x’;
char nextCh = ch;

// called auto-box
// called auto-unbox

• Java 5.0 generics also reduce explicit casts

Chapter 3: Inheritance and Class Hierarchies

32
The Method Object.equals
• Object.equals method has parameter of type Object
public boolean equals (Object other) { ... }
• Compares two objects to determine if they are equal
• Must override equals in order to support comparison

Chapter 3: Inheritance and Class Hierarchies

33
Cloning
• Purpose analogous to cloning in biology:
• Create an independent copy of an object
• Initially, objects and clone store same information
• You can change one object without affecting the other

Chapter 3: Inheritance and Class Hierarchies

34
The Shallow Copy Problem (Before)

Chapter 3: Inheritance and Class Hierarchies

35
The Shallow Copy Problem (After)

Chapter 3: Inheritance and Class Hierarchies

36
The Object.clone Method
• Object.clone addresses the shallow copy problem
• The initial copy is a shallow copy, but ...
• For a deep copy:
• Create cloned copies of all components by ...
• Invoking their respective clone methods

Chapter 3: Inheritance and Class Hierarchies

37
The Object.clone Method (2)

Chapter 3: Inheritance and Class Hierarchies

38
The Object.clone Method (3)
public class Employee implements Cloneable {
...
public Object clone () {
try {
Employee cloned = (Employee)super.clone();
cloned.address = (Address)address.clone();
return cloned;
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
}
Chapter 3: Inheritance and Class Hierarchies

39
The Object.clone Method (4)
public class Address implements Cloneable {
...
public Object clone () {
try {
Address cloned = (Address)super.clone();
return cloned;
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
}
Chapter 3: Inheritance and Class Hierarchies

40
The Object.clone Method (5)
Employee[] company = new Employee[10];
...
Employee[] newCompany =
(Employee[])company.clone();
// need loop below for deep copy
for (int i = 0; i < newCompany.length; i++) {
newCompany[i] =
(Employee)newCompany[i].clone();
}

Chapter 3: Inheritance and Class Hierarchies

41
Multiple Inheritance, Multiple Interfaces,
and Delegation
• Multiple inheritance: the ability to extend more
than one class
• Multiple inheritance ...
• Is difficult to implement efficiently
• Can lead to ambiguity: if two parents
implement the same method, which to use?
• Therefore, Java does not allow a class to
extend more than one class

Chapter 3: Inheritance and Class Hierarchies

42
Multiple Interfaces can Emulate
Multiple Inheritance
• A class can implement two or more interfaces
• Multiple interfaces emulate multiple inheritance

Desired,
but illegal,
situation

Chapter 3: Inheritance and Class Hierarchies

43
Multiple Interfaces can Emulate
Multiple Inheritance
• Approximating the desire with interfaces:

Chapter 3: Inheritance and Class Hierarchies

44
Supporting Reuse Using Delegation
• Reduce “cut and paste polymorphism”: copied code
• Idea: Object of another class does the work
• Delegation: original object delegates to the other

Chapter 3: Inheritance and Class Hierarchies

45
Delegation: Implementing It
• Class StudentWorker implements interfaces
StudentInt and EmployeeInt
• Class StudentWorker has-a Student and has-an
Employee
• StudentWorker implements (some) StudentInt
methods with calls to its Student object
• Likewise for EmployeeInt methods
• StudentWorker implements getName() itself, etc.
Chapter 3: Inheritance and Class Hierarchies

46
Delegation: More About It
• Delegation is like applying hierarchy ideas to
instances rather than classes
• There have been whole OO languages based more on
delegation than on classes
• Opinion: Classes are better, when they can do what
you need
• Downside of delegation: Not as efficient, because of
level of indirection, and need for separate objects

Chapter 3: Inheritance and Class Hierarchies

47
Packages and Directories
•
•
•
•

A Java package is a group of cooperating classes
Java programs are organized into packages
The Java API is also organized as packages
Indicate the package of a class at the top of the file:
package thePackageForThisClass;
• Classes of the same package should be
in the same directory (folder)
• Classes in the same folder must be
in the same package
Chapter 3: Inheritance and Class Hierarchies

48
Packages and Visibility
• Classes not part of a package can access only
public members of classes in the package
• The default visibility is package visbility
• Has no keyword: indicate by not using another
• Others are: public, protected, private
• Package visibility: between private and protected
• Items with package visibility: visible in package,
invisible outside package
• Items with protected visibility: visible in package
and in subclasses outside the package
Chapter 3: Inheritance and Class Hierarchies

49
The No-Package-Declared Environment
• There is a default package
• It contains files that have no package declared
• Default package ok for small projects
• Packages good for larger groups of classes

Chapter 3: Inheritance and Class Hierarchies

50
Visibility Supports Encapsulation
• Visibility rules enforce encapsulation in Java
• private: Good for members that should be
invisible even in subclasses
• package: Good to shield classes and members
from classes outside the package
• protected: Good for visibility to extenders of
classes in the package
• public: Good for visibility to all
Chapter 3: Inheritance and Class Hierarchies

51
Visibility Supports Encapsulation (2)
• Encapsulation provides insulation against change
• Greater visibility means less encapsulation
• So: use minimum visibility possible for getting the
job done!

Chapter 3: Inheritance and Class Hierarchies

52
Visibility Supports Encapsulation (3)

Chapter 3: Inheritance and Class Hierarchies

53
A Shape Class Hierarchy

Chapter 3: Inheritance and Class Hierarchies

54
A Shape Class Hierarchy (2)

Chapter 3: Inheritance and Class Hierarchies

55
A Shape Class Hierarchy (3)

Abstract
classes

Chapter 3: Inheritance and Class Hierarchies

56
A Shape Class Hierarchy (4)

Chapter 3: Inheritance and Class Hierarchies

57
A Shape Class Hierarchy (5)

DrawableRectangle
delegates shape methods,
such as ComputeArea,
to Rectangle

Chapter 3: Inheritance and Class Hierarchies

58
A Shape Class Hierarchy (6)

Chapter 3: Inheritance and Class Hierarchies

59
A Shape Class Hierarchy (7)

Chapter 3: Inheritance and Class Hierarchies

60
A Shape Class Hierarchy (8)

Chapter 3: Inheritance and Class Hierarchies

61
A Shape Class Hierarchy (9)

Chapter 3: Inheritance and Class Hierarchies

62
Object Factories
• Object factory: method that creates instances
of other classes
• Object factories are useful when:
• The necessary parameters are not known or
must be derived via computation
• The appropriate implementation should be
selected at run time as the result of some
computation

Chapter 3: Inheritance and Class Hierarchies

63
Example Object Factory
public static ShapeInt getShape () {
String figType = JOptionPane....();
if (figType.equalsIgnoreCase(“c”)) {
return new Circle();
} else if (figType.equalsIgnoreCase(“r”)) {
return new Rectangle();
} else if (figType.equalsIgnoreCase(“t”)) {
return new RtTriangle();
} else {
return null;
}
}
Chapter 3: Inheritance and Class Hierarchies

64

Weitere ähnliche Inhalte

Was ist angesagt?

04 Java Language And OOP Part IV
04 Java Language And OOP Part IV04 Java Language And OOP Part IV
04 Java Language And OOP Part IVHari Christian
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritanceKalai Selvi
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfacesDevaKumari Vijay
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#foreverredpb
 
Java Basics
Java BasicsJava Basics
Java BasicsF K
 
Java Programming - Inheritance
Java Programming - InheritanceJava Programming - Inheritance
Java Programming - InheritanceOum Saokosal
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingShivam Singhal
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritanceteach4uin
 
03 Java Language And OOP Part III
03 Java Language And OOP Part III03 Java Language And OOP Part III
03 Java Language And OOP Part IIIHari Christian
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: InheritanceTareq Hasan
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in JavaKurapati Vishwak
 
Java Programming - Polymorphism
Java Programming - PolymorphismJava Programming - Polymorphism
Java Programming - PolymorphismOum Saokosal
 
05 Java Language And OOP Part V
05 Java Language And OOP Part V05 Java Language And OOP Part V
05 Java Language And OOP Part VHari Christian
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingNithyaN19
 
Seminar on java
Seminar on javaSeminar on java
Seminar on javashathika
 

Was ist angesagt? (20)

04 Java Language And OOP Part IV
04 Java Language And OOP Part IV04 Java Language And OOP Part IV
04 Java Language And OOP Part IV
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfaces
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java Programming - Inheritance
Java Programming - InheritanceJava Programming - Inheritance
Java Programming - Inheritance
 
Java Notes
Java NotesJava Notes
Java Notes
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
LISP:Object System Lisp
LISP:Object System LispLISP:Object System Lisp
LISP:Object System Lisp
 
03 Java Language And OOP Part III
03 Java Language And OOP Part III03 Java Language And OOP Part III
03 Java Language And OOP Part III
 
Java unit2
Java unit2Java unit2
Java unit2
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in Java
 
Java Programming - Polymorphism
Java Programming - PolymorphismJava Programming - Polymorphism
Java Programming - Polymorphism
 
05 Java Language And OOP Part V
05 Java Language And OOP Part V05 Java Language And OOP Part V
05 Java Language And OOP Part V
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
 
Seminar on java
Seminar on javaSeminar on java
Seminar on java
 

Ähnlich wie Lecture d-inheritance

Object Oriented Programming.pptx
Object Oriented Programming.pptxObject Oriented Programming.pptx
Object Oriented Programming.pptxSAICHARANREDDYN
 
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.pptAshwathGupta
 
10 - Encapsulation(object oriented programming)- java . ppt
10 - Encapsulation(object oriented programming)- java . ppt10 - Encapsulation(object oriented programming)- java . ppt
10 - Encapsulation(object oriented programming)- java . pptVhlRddy
 
Ch 2 Library Classes.pdf
Ch 2 Library Classes.pdfCh 2 Library Classes.pdf
Ch 2 Library Classes.pdfKavitaHegde4
 
Ch 2 Library Classes.pptx
Ch 2 Library Classes.pptxCh 2 Library Classes.pptx
Ch 2 Library Classes.pptxKavitaHegde4
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaRadhika Talaviya
 
full defination of final opp.pptx
full defination of final opp.pptxfull defination of final opp.pptx
full defination of final opp.pptxrayanbabur
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritancemcollison
 

Ähnlich wie Lecture d-inheritance (20)

Object Oriented Programming.pptx
Object Oriented Programming.pptxObject Oriented Programming.pptx
Object Oriented Programming.pptx
 
Java OOPs
Java OOPs Java OOPs
Java OOPs
 
4-OOPS.pptx
4-OOPS.pptx4-OOPS.pptx
4-OOPS.pptx
 
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Lecture 8 Library classes
Lecture 8 Library classesLecture 8 Library classes
Lecture 8 Library classes
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Java
JavaJava
Java
 
Ch5 inheritance
Ch5 inheritanceCh5 inheritance
Ch5 inheritance
 
10 - Encapsulation(object oriented programming)- java . ppt
10 - Encapsulation(object oriented programming)- java . ppt10 - Encapsulation(object oriented programming)- java . ppt
10 - Encapsulation(object oriented programming)- java . ppt
 
Ch 2 Library Classes.pdf
Ch 2 Library Classes.pdfCh 2 Library Classes.pdf
Ch 2 Library Classes.pdf
 
Ch 2 Library Classes.pptx
Ch 2 Library Classes.pptxCh 2 Library Classes.pptx
Ch 2 Library Classes.pptx
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
 
Inheritance.ppt
Inheritance.pptInheritance.ppt
Inheritance.ppt
 
full defination of final opp.pptx
full defination of final opp.pptxfull defination of final opp.pptx
full defination of final opp.pptx
 
29c
29c29c
29c
 
29csharp
29csharp29csharp
29csharp
 
PPT Lecture-1.4.pptx
PPT Lecture-1.4.pptxPPT Lecture-1.4.pptx
PPT Lecture-1.4.pptx
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritance
 

Mehr von Tej Kiran

Transactional Analysis and Communction
Transactional Analysis and CommunctionTransactional Analysis and Communction
Transactional Analysis and CommunctionTej Kiran
 
Organizational communication
Organizational communicationOrganizational communication
Organizational communicationTej Kiran
 
Leadership and group
Leadership and groupLeadership and group
Leadership and groupTej Kiran
 
Internal and external
Internal   and   externalInternal   and   external
Internal and externalTej Kiran
 
Barriers in communication
Barriers in communicationBarriers in communication
Barriers in communicationTej Kiran
 
communtication
 communtication communtication
communticationTej Kiran
 
Partnership accounts
Partnership accountsPartnership accounts
Partnership accountsTej Kiran
 
Basics of company accounts and issue of shares
Basics of company accounts and issue of sharesBasics of company accounts and issue of shares
Basics of company accounts and issue of sharesTej Kiran
 
Amalgamation and absorption
Amalgamation and absorptionAmalgamation and absorption
Amalgamation and absorptionTej Kiran
 
Cash flow statement
Cash flow statementCash flow statement
Cash flow statementTej Kiran
 
Water resources in india
Water resources in indiaWater resources in india
Water resources in indiaTej Kiran
 
Role of govt in environment
Role of govt in environmentRole of govt in environment
Role of govt in environmentTej Kiran
 
Population growth & its effect on environment
Population growth & its effect on environmentPopulation growth & its effect on environment
Population growth & its effect on environmentTej Kiran
 
Noise pollution
Noise pollutionNoise pollution
Noise pollutionTej Kiran
 
Natural resources
Natural resourcesNatural resources
Natural resourcesTej Kiran
 
Environmental activism
Environmental activismEnvironmental activism
Environmental activismTej Kiran
 

Mehr von Tej Kiran (20)

Transactional Analysis and Communction
Transactional Analysis and CommunctionTransactional Analysis and Communction
Transactional Analysis and Communction
 
Organizational communication
Organizational communicationOrganizational communication
Organizational communication
 
Leadership
LeadershipLeadership
Leadership
 
Leadership and group
Leadership and groupLeadership and group
Leadership and group
 
Leadership
Leadership Leadership
Leadership
 
Internal and external
Internal   and   externalInternal   and   external
Internal and external
 
Barriers in communication
Barriers in communicationBarriers in communication
Barriers in communication
 
communtication
 communtication communtication
communtication
 
Partnership accounts
Partnership accountsPartnership accounts
Partnership accounts
 
Basics of company accounts and issue of shares
Basics of company accounts and issue of sharesBasics of company accounts and issue of shares
Basics of company accounts and issue of shares
 
Amalgamation and absorption
Amalgamation and absorptionAmalgamation and absorption
Amalgamation and absorption
 
Cash flow statement
Cash flow statementCash flow statement
Cash flow statement
 
Water resources in india
Water resources in indiaWater resources in india
Water resources in india
 
Solid waste
Solid wasteSolid waste
Solid waste
 
Role of govt in environment
Role of govt in environmentRole of govt in environment
Role of govt in environment
 
Population growth & its effect on environment
Population growth & its effect on environmentPopulation growth & its effect on environment
Population growth & its effect on environment
 
Noise pollution
Noise pollutionNoise pollution
Noise pollution
 
Natural resources
Natural resourcesNatural resources
Natural resources
 
Iso
IsoIso
Iso
 
Environmental activism
Environmental activismEnvironmental activism
Environmental activism
 

Kürzlich hochgeladen

Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...lizamodels9
 
Investment in The Coconut Industry by Nancy Cheruiyot
Investment in The Coconut Industry by Nancy CheruiyotInvestment in The Coconut Industry by Nancy Cheruiyot
Investment in The Coconut Industry by Nancy Cheruiyotictsugar
 
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptxContemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptxMarkAnthonyAurellano
 
Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737Riya Pathan
 
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...lizamodels9
 
Organizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessOrganizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessSeta Wicaksana
 
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCRashishs7044
 
MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?Olivia Kresic
 
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCRashishs7044
 
Pitch Deck Teardown: Geodesic.Life's $500k Pre-seed deck
Pitch Deck Teardown: Geodesic.Life's $500k Pre-seed deckPitch Deck Teardown: Geodesic.Life's $500k Pre-seed deck
Pitch Deck Teardown: Geodesic.Life's $500k Pre-seed deckHajeJanKamps
 
Call Girls Miyapur 7001305949 all area service COD available Any Time
Call Girls Miyapur 7001305949 all area service COD available Any TimeCall Girls Miyapur 7001305949 all area service COD available Any Time
Call Girls Miyapur 7001305949 all area service COD available Any Timedelhimodelshub1
 
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,noida100girls
 
Market Sizes Sample Report - 2024 Edition
Market Sizes Sample Report - 2024 EditionMarket Sizes Sample Report - 2024 Edition
Market Sizes Sample Report - 2024 EditionMintel Group
 
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCRashishs7044
 
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607dollysharma2066
 
Marketplace and Quality Assurance Presentation - Vincent Chirchir
Marketplace and Quality Assurance Presentation - Vincent ChirchirMarketplace and Quality Assurance Presentation - Vincent Chirchir
Marketplace and Quality Assurance Presentation - Vincent Chirchirictsugar
 
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City GurgaonCall Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaoncallgirls2057
 
Islamabad Escorts | Call 03070433345 | Escort Service in Islamabad
Islamabad Escorts | Call 03070433345 | Escort Service in IslamabadIslamabad Escorts | Call 03070433345 | Escort Service in Islamabad
Islamabad Escorts | Call 03070433345 | Escort Service in IslamabadAyesha Khan
 
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607dollysharma2066
 
/:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In...
/:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In.../:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In...
/:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In...lizamodels9
 

Kürzlich hochgeladen (20)

Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
 
Investment in The Coconut Industry by Nancy Cheruiyot
Investment in The Coconut Industry by Nancy CheruiyotInvestment in The Coconut Industry by Nancy Cheruiyot
Investment in The Coconut Industry by Nancy Cheruiyot
 
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptxContemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
 
Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737
 
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
 
Organizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessOrganizational Structure Running A Successful Business
Organizational Structure Running A Successful Business
 
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
 
MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?
 
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
 
Pitch Deck Teardown: Geodesic.Life's $500k Pre-seed deck
Pitch Deck Teardown: Geodesic.Life's $500k Pre-seed deckPitch Deck Teardown: Geodesic.Life's $500k Pre-seed deck
Pitch Deck Teardown: Geodesic.Life's $500k Pre-seed deck
 
Call Girls Miyapur 7001305949 all area service COD available Any Time
Call Girls Miyapur 7001305949 all area service COD available Any TimeCall Girls Miyapur 7001305949 all area service COD available Any Time
Call Girls Miyapur 7001305949 all area service COD available Any Time
 
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
 
Market Sizes Sample Report - 2024 Edition
Market Sizes Sample Report - 2024 EditionMarket Sizes Sample Report - 2024 Edition
Market Sizes Sample Report - 2024 Edition
 
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
 
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
 
Marketplace and Quality Assurance Presentation - Vincent Chirchir
Marketplace and Quality Assurance Presentation - Vincent ChirchirMarketplace and Quality Assurance Presentation - Vincent Chirchir
Marketplace and Quality Assurance Presentation - Vincent Chirchir
 
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City GurgaonCall Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
 
Islamabad Escorts | Call 03070433345 | Escort Service in Islamabad
Islamabad Escorts | Call 03070433345 | Escort Service in IslamabadIslamabad Escorts | Call 03070433345 | Escort Service in Islamabad
Islamabad Escorts | Call 03070433345 | Escort Service in Islamabad
 
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
 
/:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In...
/:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In.../:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In...
/:Call Girls In Indirapuram Ghaziabad ➥9990211544 Independent Best Escorts In...
 

Lecture d-inheritance

  • 1. Inheritance and Class Hierarchies Based on Koffmann and Wolfgang
  • 2. Chapter Outline • Inheritance and how it facilitates code reuse • How does Java find the “right” method to execute? • (When more than one has the same name ...) • Defining and using abstract classes • Class Object: its methods and how to override them • How to “clone” an object • The difference between: • A true clone (deep copy) and • A shallow copy Chapter 3: Inheritance and Class Hierarchies 2
  • 3. Chapter Outline (2) • Why Java does not implement multiple inheritance • Get some of the advantages of multiple inheritance: • Interfaces • Delegation • Sample class hierarchy: drawable shapes • An object factory and how to use it • Creating packages • Code visibility Chapter 3: Inheritance and Class Hierarchies 3
  • 4. Inheritance and Class Hierarchies • Object-oriented programming (OOP) is popular because: • It enables reuse of previous code saved as classes • All Java classes are arranged in a hierarchy • Object is the superclass of all Java classes • Inheritance and hierarchical organization capture idea: • One thing is a refinement or extension of another Chapter 3: Inheritance and Class Hierarchies 4
  • 5. Inheritance and Class Hierarchies (2) superclass subclass Chapter 3: Inheritance and Class Hierarchies 5
  • 6. Is-a Versus Has-a Relationships • Confusing has-a and is-a leads to misusing inheritance • Model a has-a relationship with an attribute (variable) public class C { ... private B part; ...} • Model an is-a relationship with inheritance • If every C is-a B then model C as a subclass of B • Show this: in C include extends B: public class C extends B { ... } Chapter 3: Inheritance and Class Hierarchies 6
  • 7. A Superclass and a Subclass • Consider two classes: Computer and Laptop • A laptop is a kind of computer: therefore a subclass methods of Computer and all subclasses additional Methods for class Laptop (and its subclasses) variables of Computer and all subclasses additional variables for class Laptop (and its subclasses) Chapter 3: Inheritance and Class Hierarchies 7
  • 8. Illustrating Has-a with Computer public class Computer { private Memory mem; ... } A Computer has only one Memory But neither is-a the other public class Memory { private int size; private int speed; private String kind; ... } Chapter 3: Inheritance and Class Hierarchies 8
  • 9. Initializing Data Fields in a Subclass • What about data fields of a superclass? • Initialize them by invoking a superclass constructor with the appropriate parameters • If the subclass constructor skips calling the superclass ... • Java automatically calls the no-parameter one • Point: Insure superclass fields initialized before subclass starts to initialize its part of the object Chapter 3: Inheritance and Class Hierarchies 9
  • 10. Example of Initializing Subclass Data public class Computer { private String manufacturer; ... public Computer (String manufacturer, ...) { this.manufacturer = manufacturer; ... } } public class Laptop extends Computer { private double weight; ... public Laptop (String manufacturer, ..., double weight, ...) { super(manufacturer, ...); this.weight = weight; } } Chapter 3: Inheritance and Class Hierarchies 10
  • 11. Protected Visibility for Superclass Data • private data are not accessible to subclasses! • protected data fields accessible in subclasses (Technically, accessible in same package) • Subclasses often written by others, and • Subclasses should avoid relying on superclass details • So ... in general, private is better Chapter 3: Inheritance and Class Hierarchies 11
  • 12. Method Overriding • If subclass has a method of a superclass (same signature), that method overrides the superclass method: public class A { ... public int M (float f, String s) { bodyA } } public class B extends A { ... public int M (float f, String s) { bodyB } } • If we call M on an instance of B (or subclass of B), bodyB runs • In B we can access bodyA with: super.M(...) • The subclass M must have same return type as superclass M Chapter 3: Inheritance and Class Hierarchies 12
  • 13. Method Overloading • Method overloading: multiple methods ... • With the same name • But different signatures • In the same class • Constructors are often overloaded • Example: • MyClass (int inputA, int inputB) • MyClass (float inputA, float inputB) Chapter 3: Inheritance and Class Hierarchies 13
  • 14. Example of Overloaded Constructors public class Laptop extends Computer { private double weight; ... public Laptop (String manufacturer, String processor, ..., double weight, ...) { super(manufacturer, processor, ...); this.weight = weight; } public Laptop (String manufacturer, ..., double weight, ...) { this(manufacturer, “Pentium”, ..., weight, ...); } } Chapter 3: Inheritance and Class Hierarchies 14
  • 15. Overloading Example From Java Library ArrayList has two remove methods: remove (int position) • Removes object that is at a specified place in the list remove (Object obj) • Removes a specified object from the list It also has two add methods: add • add • (Element e) Adds new object to the end of the list (int index, Element e) Adds new object at a specified place in the list Chapter 3: Inheritance and Class Hierarchies 15
  • 16. Polymorphism • Variable of superclass type can refer to object of subclass type • Polymorphism means “many forms” or “many shapes” • Polymorphism lets the JVM determine at run time which method to invoke • At compile time: • Java compiler cannot determine exact type of the object • But it is known at run time • Compiler knows enough for safety: the attributes of the type • Subclasses guaranteed to obey Chapter 3: Inheritance and Class Hierarchies 16
  • 17. Interfaces vs Abstract Classes vs Concrete Classes • A Java interface can declare methods • But cannot implement them • Methods of an interface are called abstract methods • An abstract class can have: • Abstract methods (no body) • Concrete methods (with body) • Data fields • Unlike a concrete class, an abstract class ... • Cannot be instantiated • Can declare abstract methods • Which must be implemented in all concrete subclasses Chapter 3: Inheritance and Class Hierarchies 17
  • 18. Abstract Classes and Interfaces • Abstract classes and interfaces cannot be instantiated • An abstract class can have constructors! • Purpose: initialize data fields when a subclass object is created • Subclass uses super(…) to call the constructor • An abstract class may implement an interface • But need not define all methods of the interface • Implementation of them is left to subclasses Chapter 3: Inheritance and Class Hierarchies 18
  • 19. Example of an Abstract Class public abstract class Food { public final String name; private double calories; public double getCalories () { return calories; } protected Food (String name, double calories) { this.name = name; this.calories = calories; } public abstract double percentProtein(); public abstract double percentFat(); public abstract double percentCarbs(); } Chapter 3: Inheritance and Class Hierarchies 19
  • 20. Example of a Concrete Subclass public class Meat extends Food { private final double protCal; ...; public Meat (String name, double protCal, double fatCal double carbCal) { super(name, protCal+fatCal+carbCal); this.protCal = protCal; ...; } public double percentProtein () { return 100.0 * (protCal / getCalories()); } ...; } Chapter 3: Inheritance and Class Hierarchies 20
  • 21. Example: Number and the Wrapper Classes Declares what the (concrete) subclasses have in common Chapter 3: Inheritance and Class Hierarchies 21
  • 22. Inheriting from Interfaces vs Classes • A class can extend 0 or 1 superclass • Called single inheritance • An interface cannot extend a class at all • (Because it is not a class) • A class or interface can implement 0 or more interfaces • Called multiple inheritance Chapter 3: Inheritance and Class Hierarchies 22
  • 23. Summary of Features of Actual Classes, Abstract Classes, and Interfaces Chapter 3: Inheritance and Class Hierarchies 23
  • 24. Class Object • Object is the root of the class hierarchy • Every class has Object as a superclass • All classes inherit the methods of Object • But may override them Chapter 3: Inheritance and Class Hierarchies 24
  • 25. The Method toString • You should always override toString method if you want to print object state • If you do not override it: • Object.toString will return a String • Just not the String you want! Example: ArrayBasedPD@ef08879 ... The name of the class, @, instance’s hash code Chapter 3: Inheritance and Class Hierarchies 25
  • 26. Operations Determined by Type of Reference Variable • Variable can refer to object whose type is a subclass of the variable’s declared type • Type of the variable determines what operations are legal • Java is strongly typed Object athing = new Integer(25); • Compiler always verifies that variable’s type includes the class of every expression assigned to the variable Chapter 3: Inheritance and Class Hierarchies 26
  • 27. Casting in a Class Hierarchy • Casting obtains a reference of different, but matching, type • Casting does not change the object! • It creates an anonymous reference to the object Integer aNum = (Integer)aThing; • Downcast: • Cast superclass type to subclass type • Checks at run time to make sure it’s ok • If not ok, throws ClassCastException Chapter 3: Inheritance and Class Hierarchies 27
  • 28. Casting in a Class Hierarchy (2) • instanceof can guard against ClassCastException Object obj = ...; if (obj instanceof Integer) { Integer i = (Integer)obj; int val = i.intValue(); ...; } else { ... } Chapter 3: Inheritance and Class Hierarchies 28
  • 29. Downcasting From an Interface Type Collection c = new ArrayList(); ...; ... ((ArrayList)c).get(3) ... Chapter 3: Inheritance and Class Hierarchies 29
  • 30. Polymorphism Reduces Need For Type Tests // Non OO style: if (stuff[i] instanceof Integer) sum += ((Integer) stuff[i]).doubleValue(); else if (stuff[i] instanceof Double) sum += ((Double) stuff[i]).doubleValue(); ... // OO style: sum += stuff[i].doubleValue(); Chapter 3: Inheritance and Class Hierarchies 30
  • 31. Polymorphism and Type Tests (2) • Polymorphic code style is more extensible • Works automatically with new subclasses • Polymorphic code is more efficient • System does one indirect branch vs many tests • So ... uses of instanceof are suspect Chapter 3: Inheritance and Class Hierarchies 31
  • 32. Java 5.0 Reduces Explicit Conversions • Java 1.4 and earlier: Character ch = new Character(‘x’); char nextCh = ch.charValue(); • Java 5.0: Character ch = ‘x’; char nextCh = ch; // called auto-box // called auto-unbox • Java 5.0 generics also reduce explicit casts Chapter 3: Inheritance and Class Hierarchies 32
  • 33. The Method Object.equals • Object.equals method has parameter of type Object public boolean equals (Object other) { ... } • Compares two objects to determine if they are equal • Must override equals in order to support comparison Chapter 3: Inheritance and Class Hierarchies 33
  • 34. Cloning • Purpose analogous to cloning in biology: • Create an independent copy of an object • Initially, objects and clone store same information • You can change one object without affecting the other Chapter 3: Inheritance and Class Hierarchies 34
  • 35. The Shallow Copy Problem (Before) Chapter 3: Inheritance and Class Hierarchies 35
  • 36. The Shallow Copy Problem (After) Chapter 3: Inheritance and Class Hierarchies 36
  • 37. The Object.clone Method • Object.clone addresses the shallow copy problem • The initial copy is a shallow copy, but ... • For a deep copy: • Create cloned copies of all components by ... • Invoking their respective clone methods Chapter 3: Inheritance and Class Hierarchies 37
  • 38. The Object.clone Method (2) Chapter 3: Inheritance and Class Hierarchies 38
  • 39. The Object.clone Method (3) public class Employee implements Cloneable { ... public Object clone () { try { Employee cloned = (Employee)super.clone(); cloned.address = (Address)address.clone(); return cloned; } catch (CloneNotSupportedException e) { throw new InternalError(); } } } Chapter 3: Inheritance and Class Hierarchies 39
  • 40. The Object.clone Method (4) public class Address implements Cloneable { ... public Object clone () { try { Address cloned = (Address)super.clone(); return cloned; } catch (CloneNotSupportedException e) { throw new InternalError(); } } } Chapter 3: Inheritance and Class Hierarchies 40
  • 41. The Object.clone Method (5) Employee[] company = new Employee[10]; ... Employee[] newCompany = (Employee[])company.clone(); // need loop below for deep copy for (int i = 0; i < newCompany.length; i++) { newCompany[i] = (Employee)newCompany[i].clone(); } Chapter 3: Inheritance and Class Hierarchies 41
  • 42. Multiple Inheritance, Multiple Interfaces, and Delegation • Multiple inheritance: the ability to extend more than one class • Multiple inheritance ... • Is difficult to implement efficiently • Can lead to ambiguity: if two parents implement the same method, which to use? • Therefore, Java does not allow a class to extend more than one class Chapter 3: Inheritance and Class Hierarchies 42
  • 43. Multiple Interfaces can Emulate Multiple Inheritance • A class can implement two or more interfaces • Multiple interfaces emulate multiple inheritance Desired, but illegal, situation Chapter 3: Inheritance and Class Hierarchies 43
  • 44. Multiple Interfaces can Emulate Multiple Inheritance • Approximating the desire with interfaces: Chapter 3: Inheritance and Class Hierarchies 44
  • 45. Supporting Reuse Using Delegation • Reduce “cut and paste polymorphism”: copied code • Idea: Object of another class does the work • Delegation: original object delegates to the other Chapter 3: Inheritance and Class Hierarchies 45
  • 46. Delegation: Implementing It • Class StudentWorker implements interfaces StudentInt and EmployeeInt • Class StudentWorker has-a Student and has-an Employee • StudentWorker implements (some) StudentInt methods with calls to its Student object • Likewise for EmployeeInt methods • StudentWorker implements getName() itself, etc. Chapter 3: Inheritance and Class Hierarchies 46
  • 47. Delegation: More About It • Delegation is like applying hierarchy ideas to instances rather than classes • There have been whole OO languages based more on delegation than on classes • Opinion: Classes are better, when they can do what you need • Downside of delegation: Not as efficient, because of level of indirection, and need for separate objects Chapter 3: Inheritance and Class Hierarchies 47
  • 48. Packages and Directories • • • • A Java package is a group of cooperating classes Java programs are organized into packages The Java API is also organized as packages Indicate the package of a class at the top of the file: package thePackageForThisClass; • Classes of the same package should be in the same directory (folder) • Classes in the same folder must be in the same package Chapter 3: Inheritance and Class Hierarchies 48
  • 49. Packages and Visibility • Classes not part of a package can access only public members of classes in the package • The default visibility is package visbility • Has no keyword: indicate by not using another • Others are: public, protected, private • Package visibility: between private and protected • Items with package visibility: visible in package, invisible outside package • Items with protected visibility: visible in package and in subclasses outside the package Chapter 3: Inheritance and Class Hierarchies 49
  • 50. The No-Package-Declared Environment • There is a default package • It contains files that have no package declared • Default package ok for small projects • Packages good for larger groups of classes Chapter 3: Inheritance and Class Hierarchies 50
  • 51. Visibility Supports Encapsulation • Visibility rules enforce encapsulation in Java • private: Good for members that should be invisible even in subclasses • package: Good to shield classes and members from classes outside the package • protected: Good for visibility to extenders of classes in the package • public: Good for visibility to all Chapter 3: Inheritance and Class Hierarchies 51
  • 52. Visibility Supports Encapsulation (2) • Encapsulation provides insulation against change • Greater visibility means less encapsulation • So: use minimum visibility possible for getting the job done! Chapter 3: Inheritance and Class Hierarchies 52
  • 53. Visibility Supports Encapsulation (3) Chapter 3: Inheritance and Class Hierarchies 53
  • 54. A Shape Class Hierarchy Chapter 3: Inheritance and Class Hierarchies 54
  • 55. A Shape Class Hierarchy (2) Chapter 3: Inheritance and Class Hierarchies 55
  • 56. A Shape Class Hierarchy (3) Abstract classes Chapter 3: Inheritance and Class Hierarchies 56
  • 57. A Shape Class Hierarchy (4) Chapter 3: Inheritance and Class Hierarchies 57
  • 58. A Shape Class Hierarchy (5) DrawableRectangle delegates shape methods, such as ComputeArea, to Rectangle Chapter 3: Inheritance and Class Hierarchies 58
  • 59. A Shape Class Hierarchy (6) Chapter 3: Inheritance and Class Hierarchies 59
  • 60. A Shape Class Hierarchy (7) Chapter 3: Inheritance and Class Hierarchies 60
  • 61. A Shape Class Hierarchy (8) Chapter 3: Inheritance and Class Hierarchies 61
  • 62. A Shape Class Hierarchy (9) Chapter 3: Inheritance and Class Hierarchies 62
  • 63. Object Factories • Object factory: method that creates instances of other classes • Object factories are useful when: • The necessary parameters are not known or must be derived via computation • The appropriate implementation should be selected at run time as the result of some computation Chapter 3: Inheritance and Class Hierarchies 63
  • 64. Example Object Factory public static ShapeInt getShape () { String figType = JOptionPane....(); if (figType.equalsIgnoreCase(“c”)) { return new Circle(); } else if (figType.equalsIgnoreCase(“r”)) { return new Rectangle(); } else if (figType.equalsIgnoreCase(“t”)) { return new RtTriangle(); } else { return null; } } Chapter 3: Inheritance and Class Hierarchies 64