Inheritance and Class Hierarchies Chapter 3 Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.

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

OOP: Inheritance By: Lamiaa Said.
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
ITEC200 – Week03 Inheritance and Class Hierarchies.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 Chapter 12 More OOP, Interfaces, and Inner Classes.
INF 523Q Chapter 7: Inheritance. 2 Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and.
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.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Chapter 10 Classes Continued
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
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.
INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Predefined Classes in Java Ellen Walker CPSC 201 Data Structures Hiram College.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Inheritance in the Java programming language J. W. Rider.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Lists and the Collection Interface Review inheritance & collections.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Programming in Java CSCI-2220 Object Oriented Programming.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Inheritance and Access Control CS 162 (Summer 2009)
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
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.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
Inheritance ndex.html ndex.htmland “Java.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Object-Oriented Programming: Polymorphism Chapter 10.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
1 Inheritance One of the goals of object oriented programming is code reuse. Inheritance is one mechanism for accomplishing code reuse. It allows us to.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Class Inheritance Part II: Overriding and Polymorphism Corresponds with Chapter 10.
Modern Programming Tools And Techniques-I
Inheritance and Polymorphism
Data Structures and Algorithms
Friday, January 26, 2018 Announcements… For Today… For Next Time…
Computer Science II Exam 1 Review.
3.3 Abstract Classes, Assignment, and Casting in a Hierarchy
Extending Classes.
Presentation transcript:

Inheritance and Class Hierarchies Chapter 3

Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates code reuse To understand how Java determines which method to execute when there are multiple methods with the same name in a class hierarchy To learn how to define and use abstract classes as base classes in a hierarchy To study class Object and its methods and to learn how to override them To learn how to “clone” an object and to understand the difference between a true clone (deep copy) and a shallow copy

Chapter 3: Inheritance and Class Hierarchies3 Chapter Objectives (continued) To understand why Java does not implement multiple inheritance and to see how you can gain some of the advantages of multiple inheritance through interfaces and delegation To become familiar with a class hierarchy for drawable shapes To be introduced to an object factory and to learn how to use it To understand how to create packages and to learn more about visibility

Chapter 3: Inheritance and Class Hierarchies4 Introduction to Inheritance and Class Hierarchies Popularity of OOP is that it enables programmers to reuse previously written code saved as classes All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous to inheritance in humans Inheritance and hierarchical organization allow you to capture the idea that one thing may be a refinement or extension of another

Chapter 3: Inheritance and Class Hierarchies5

6 Is-a Versus Has-a Relationships One misuse of inheritance is confusing the has-a relationship with the is-a relationship The has-a relationship means that one class has the second class as an attribute We can combine is-a and has-a relationships The keyword extends specifies that one class is a subclass of another

Chapter 3: Inheritance and Class Hierarchies7 A Superclass and a Subclass Consider two classes: Computer and Laptop A laptop is a kind of computer and is therefore a subclass of computer

Chapter 3: Inheritance and Class Hierarchies8 Class Computer and use of this. public class Computer { // Data Fields private String manufacturer; private String processor; private int ramSize; private int diskSize; public Computer(String man, String processor, int ram, int disk) { manufacturer = man; this.processor = processor; ramSize = ram; diskSize = disk; } Why not processor = processor; Instead of this.processor = processor;

Chapter 3: Inheritance and Class Hierarchies9 Class Laptop Laptop “is a” computer Class Laptop is a subclass of Computer public class LapTop extends Computer { // Data Fields private static final String DEFAULT_LT_MAN = "MyBrand"; private double screenSize; private double weight;..... Laptop also inherits data fields from Computer

Chapter 3: Inheritance and Class Hierarchies10 Initializing Data Fields in a Subclass and the No-Parameter Constructor Private data fields belonging to a base class must be initialized by invoking the base class’s constructor with the appropriate parameters If the execution of any constructor in a subclass does not invoke a superclass constructor, Java automatically invokes the no-parameter constructor for the superclass Initializes that part of the object inherited from the superclass before the subclass starts to initialize its part of the object

Chapter 3: Inheritance and Class Hierarchies11 Class Laptop Must use superclass constructor to initialize data fields private to superclass 1st statement of constructor body… public LapTop(String man, String proc, int ram, int disk, double screen, double wei) { super(man, proc, ram, disk); screenSize = screen; weight = wei; } …otherwise, the “no parameter constructor” of superclass invoked by default

Chapter 3: Inheritance and Class Hierarchies12 Protected Visibility for Superclass Data Fields Private data fields are not accessible to derived classes Protected visibility allows data fields to be accessed either by the class defining it or any subclass In general, it is better to use private visibility because subclasses may be written by different programmers and it is always good practice to restrict and control access to the superclass data fields

Chapter 3: Inheritance and Class Hierarchies13 Method Overriding If a derived class (subclass) has a method found in its base class, method will override the base class method The keyword super can be used to gain access to superclass methods overridden by the base class A subclass method must have the same return type as the corresponding superclass method

Chapter 3: Inheritance and Class Hierarchies14 Method Overriding Suppose main is… public static void main(String[] args) { Computer myComputer = new Computer(“Acme”,“Intel P4”,512, 60); LapTop yourComputer = new LapTop(“Dell”,AMD”,256,40,15.0,7.5); System.out.println(“My computer is: \n” + myComputer.toString()); System.out.println(“Your computer is: \n” + yourComputer.toString()); } Suppose Computer defines toString, but LapTop does not So, what is printed by 2nd println?

Chapter 3: Inheritance and Class Hierarchies15 Method Overriding Probably want to override toString in LapTop… public String toString() { String result = super.toString() + “/nScreen size: ” + screenSize + “ inches” + “/nWeight: ” + weight + “ pounds” } Note that overridden method must have same return type

Chapter 3: Inheritance and Class Hierarchies16 Method Overloading Method overloading: having multiple methods with the same name but different signatures in a class Constructors are often overloaded For example: MyClass(int inputA, int inputB) MyClass(int inputA, int inputB, double inputC) Then there are 2 ways to call MyClass

Chapter 3: Inheritance and Class Hierarchies17 Polymorphism A variable of a superclass type can reference an object of a subclass type E.g., variable of Computer type can reference LapTop Polymorphism means many forms or many shapes Polymorphism allows the JVM to determine which method to invoke at run time At compile time, the Java compiler can’t determine what type of object a superclass may reference but it is known at run time

Chapter 3: Inheritance and Class Hierarchies18 Polymorphism What does the following code do? theComputer = new Computer(“Acme”,“Intel P4”,512, 60); System.out.println(theComputer.toString()); What about the following? theComputer = new LapTop(“Dell”,AMD”,256,40,15.0,7.5); System.out.println(theComputer.toString()); Which toString is called??? Gets a little trickier with arrays…

Chapter 3: Inheritance and Class Hierarchies19 Abstract Classes, Assignment, and Casting in a Hierarchy An interface can declare methods but does not provide an implementation of those methods Methods declared in an interface are called abstract methods An abstract class can have abstract methods, data fields, and actual methods Abstract class differs from a concrete class in that An abstract class cannot be instantiated An abstract class can declare abstract methods, which must be implemented in its subclasses

Chapter 3: Inheritance and Class Hierarchies20 Abstract Classes and Interfaces Like an interface, an abstract class can’t be instantiated An abstract class can have constructors to initialize its data fields when a new subclass is created Subclass uses super(…) to call the constructor May implement an interface but it doesn’t have to define all of the methods declared in the interface Implementation is left to its subclasses

Chapter 3: Inheritance and Class Hierarchies21 Abstract Class Food public abstract class Food { // Data Field private double calories; // Abstract Methods public abstract double percentProtein(); public abstract double percentFat(); public abstract double percentCarbohydrates(); // Methods public double getCalories() { return calories; } public void setCalories(double cal) { calories = cal; }

Chapter 3: Inheritance and Class Hierarchies22 Abstract Class Food Actual subclasses must implement the abstract methods public abstract double percentProtein(); public abstract double percentFat(); public abstract double percentCarbohydrates(); Cannot create type Food objects But could have, say, Food mySnack = new Vegetable(“carrot”);

Chapter 3: Inheritance and Class Hierarchies23 Abstract Class Number and the Java Wrapper Classes

Chapter 3: Inheritance and Class Hierarchies24 Summary of Features of Actual Classes, Abstract Classes, and Interfaces

Chapter 3: Inheritance and Class Hierarchies25 Class Object Object is the root of the class hierarchy; every class has Object as a superclass All classes inherit the methods defined in class Object but may be overridden

Chapter 3: Inheritance and Class Hierarchies26 The Method toString You should always override the toString method if you want to represent an object’s state If you do not override it, the toString method for class Object will return a string, but not what you expect Object’s toString method gives you the object’s class name and hash code, not its state This is (almost certainly) not what you want

Chapter 3: Inheritance and Class Hierarchies27 Operations Determined by Type of Reference Variable Suppose you have Object aThing = new Integer(25); Will this compile? Why or why not? Answer: Yes, since Object is a superclass of Integer Suppose you then have: aThing.intValue(); What happens and why? Answer: Compile time error, since Object determines which operations are allowed and Object has no intValue But wait, there’s more…

Chapter 3: Inheritance and Class Hierarchies28 Operations Determined by Type of Reference Variable As on previous slide, suppose you have Object aThing = new Integer(25); Consider this method call: aThing.equals(new Integer("25")); Will this compile? Why or why not? Answer: This will compile: Object has equals method At runtime, which equals method? Answer: At execution time, Integer’s equals method is called! Why?

Chapter 3: Inheritance and Class Hierarchies29 Java is Strongly Typed As on previous slides, suppose you have Object aThing = new Integer(25); Consiider the following: Integer aNum = aThing; Will this compile? Why or why not? Answer: No, you will get a compile time error since Java is “strongly typed” If Java allowed this to compile, it might die at runtime if you tried to use Integer (only) method on Object type Strongly Typed means Java verifies types of expressions are compatible at compile time But, there is a way around this…

Chapter 3: Inheritance and Class Hierarchies30 Casting in a Class Hierarchy Java provides casting to enable us to process one object referenced by one type through a reference variable of its actual type Casting does not change the object referenced; it creates anonymous reference to that object Can cast aThing to an Integer by (Integer) aThing Succeeds only if object referenced by aThing is type Integer Otherwise get a ClassCastException Use instanceof operator to avoid this

Chapter 3: Inheritance and Class Hierarchies31 Downcasting Downcast: cast a higher type to a lower type Higher and lower in terms of class hierarchy But lower guy must be subclass For example, Object is higher than Integer So, (Integer)aThing is a downcast Can also downcast interface types “Upcasting” is allowed, but not necessary So don’t waste your time!

Chapter 3: Inheritance and Class Hierarchies32 Java 5.0 Reduces Need for Casting Two new features that reduce the need for casting: Autoboxing/unboxing Generics Autoboxing/unboxing eases the conversion between a primitive type and its corresponding wrapper type

Chapter 3: Inheritance and Class Hierarchies33 The Method Object.equals The Object.equals method has a parameter of type Object Compares two objects to determine whether they are equal You must override the equals method if you want to be able to compare two objects of a class

Chapter 3: Inheritance and Class Hierarchies34 Cloning The purpose of cloning in object-oriented programming is analogous to cloning in biology Create an independent copy of an object Initially, both objects will store the same information For a true clone, you can change one object without affecting the other How to accomplish this?

Chapter 3: Inheritance and Class Hierarchies35 How Not to Clone Consider the following code Both e1.name and e2.name reference “Jim” Definitely not a clone!

Chapter 3: Inheritance and Class Hierarchies36 How Not to Clone

Chapter 3: Inheritance and Class Hierarchies37 Shallow Copy Suppose we try this public Object clone() { Object cloned = new Employee(name, hours, rate, address); return cloned; } Then we could do this Employee e2 = (Employee) e1.clone(); Does this create a clone? Answer: No, e2 is a copy of e1 (good), but object references are same in e1 and e2 (bad) Data fields are distinct, but not objects (next slide…)

Chapter 3: Inheritance and Class Hierarchies38 Statement e1.setAddressLine1("Room 224"); creates a new String object that is referenced by e1.address.line1 and e2.address.line1

Chapter 3: Inheritance and Class Hierarchies39 The Object.clone method Java provides the Object.clone method to solve the shallow copy problem The initial copy is a shallow copy as the current object’s data fields are copied To make a deep copy, you must create cloned copies of all components by invoking their respective clone methods Note that clone method gives shallow copy of data structure (such as an array) Read the text!

Chapter 3: Inheritance and Class Hierarchies40 The Object.clone method (continued) After e1.setAddressLine1("Room 224"); only e1.address.line1 references the new String object.

Chapter 3: Inheritance and Class Hierarchies41 Employee.clone()

Chapter 3: Inheritance and Class Hierarchies42 Address.clone()

Chapter 3: Inheritance and Class Hierarchies43 Multiple Inheritance, Multiple Interfaces, and Delegation Multiple inheritance: the ability to extend more than one class Multiple inheritance is a language feature that is difficult to implement and can lead to ambiguity Therefore, Java does not allow a class to extend more than one class

Chapter 3: Inheritance and Class Hierarchies44 Using Multiple Interfaces to Emulate Multiple Inheritance If we define two interfaces, a class can implement both Multiple interfaces emulate multiple inheritance

Chapter 3: Inheritance and Class Hierarchies45 Using Multiple Interfaces to Emulate Multiple Inheritance (continued)

Chapter 3: Inheritance and Class Hierarchies46 Implementing Reuse Through Delegation You can reduce duplication of modifications and reduce problems associated with version control through a technique known as delegation In delegation, a method of one class accomplishes an operation by delegating it to a method of another class

Chapter 3: Inheritance and Class Hierarchies47 Implementing Reuse Through Delegation For example, can use Student getGPA method in StudentWorker Why is this useful? If getGPA changes, only need to change in 1 place

Chapter 3: Inheritance and Class Hierarchies48 Packages The Java API is organized into packages The package is declared by the first statement in the file in which the class is defined Keyword package followed by the package name All classes in the same package must be stored in the same directory or folder Classes that are not part of a package may access only public members of classes in the package

Chapter 3: Inheritance and Class Hierarchies49 The No-Package-Declared Environment and Package Visibility There exists a default package Files that do not specify a package are considered part of the default package If you don’t declare packages, all of your packages belong to the same, default package Package visibility sits between private and protected Classes, data fields, and methods with package visibility are accessible to all other methods of the same package but are not accessible to methods outside of the package Classes, data fields, and methods that are declared protected are visible to all members of the package

Chapter 3: Inheritance and Class Hierarchies50 Visibility Supports Encapsulation Visibility and encapsulation in a Java program private visibility is for members of a class that should not be accessible outside the class Not even classes that extend the class (subclasses) package visibility allows the developer of a library to shield classes and class members from classes outside the package protected visibility allows the package developer to give control to programs that extend classes in the package Even subclasses that are outside the package

Chapter 3: Inheritance and Class Hierarchies51 Visibility Supports Encapsulation (continued)

Chapter 3: Inheritance and Class Hierarchies52 A Shape Class Hierarchy

Chapter 3: Inheritance and Class Hierarchies53 A Shape Class Hierarchy (continued)

Chapter 3: Inheritance and Class Hierarchies54

Chapter 3: Inheritance and Class Hierarchies55 A Shape Class Hierarchy (continued)

Chapter 3: Inheritance and Class Hierarchies56 Object Factories An object factory is a 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 of an interface or abstract class should be selected as the result of some computation

Chapter 3: Inheritance and Class Hierarchies57 Object Factories (continued)

Chapter 3: Inheritance and Class Hierarchies58 Chapter Review Inheritance and class hierarchies to capture the idea that one thing may be a refinement or extension of another Encapsulation and inheritance impose structure on object abstractions The keyword interface defines an interface The keyword abstract defines an abstract class or method Delegation gains some of the advantages of multiple inheritance Visibility is influenced by the package in which a class is declared