Reusing Classes 2015-12-81. composition The trick is to use the classes without soiling the existing code. In this chapter you’ll see two ways to accomplish.

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
CSE 1302 Lecture 8 Inheritance Richard Gesick Figures from Deitel, “Visual C#”, Pearson.
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
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.
Road Map Introduction to object oriented programming. Classes
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
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.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Chapter 10 Classes Continued
© 2006 Pearson Addison-Wesley. All rights reserved9 A-1 Chapter 9 Advanced Java Topics CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2007.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
Object Based Programming. Summary Slide  Instantiating An Object  Encapsulation  Inheritance  Polymorphism –Overriding Methods –Overloading vs. Overriding.
Using Classes Object-Oriented Programming Using C++ Second Edition 5.
Programming Languages and Paradigms Object-Oriented Programming.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
Chapter 8 More Object Concepts
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.
Chapter 9 Defining New Types. Objectives Explore the use of member functions when creating a struct. Introduce some of the concepts behind object-oriented.
Recap (önemli noktaları yinelemek) from last week Paradigm Kay’s Description Intro to Objects Messages / Interconnections Information Hiding Classes Inheritance.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
Initialization & Cleanup Guaranteed initialization with the constructor The name of the constructor is the same as the name of the class.
CS212: Object Oriented Analysis and Design Lecture 15: Inheritance in C++ -II.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Everything Is an Object Manipulate objects with references The identifier you manipulate is actually a “reference” to an object. Like a television.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Programming in Java CSCI-2220 Object Oriented Programming.
Object Oriented Software Development
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
1 Chapter Four Creating and Using Classes. 2 Objectives Learn about class concepts How to create a class from which objects can be instantiated Learn.
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)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Object-Oriented Programming Chapter Chapter
Chapter 10: Introduction to Inheritance. Objectives Learn about the concept of inheritance Extend classes Override superclass methods Call constructors.
Interfaces About Interfaces Interfaces and abstract classes provide more structured way to separate interface from implementation
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
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
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Georgia Institute of Technology More on Creating Classes part 3 Barb Ericson Georgia Institute of Technology Nov 2005.
Java Software Solutions Lewis and Loftus Chapter 8 Copyright 1997 by John Lewis and William Loftus. All rights reserved. 1 Inheritance -- Introduction.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
Part -1 © by Pearson Education, Inc. All Rights Reserved.
Java Inheritance.
Polymorphism 2019/4/29.
Presentation transcript:

Reusing Classes

composition The trick is to use the classes without soiling the existing code. In this chapter you’ll see two ways to accomplish this. The first is quite straightforward: you simply create objects of your existing class inside the new class. This is called composition, because the new class is composed of objects of existing classes. You’re simply reusing the functionality of the code, not its form

inheritance Literally take the form of the existing class and add code to it without modifying the existing class. Inheritance is one of the cornerstones of object-oriented programming, and has additional implications

Composition syntax You simply place object references inside new classes. If you want the references initialized, you can do it: 1. At the point the objects are defined. 2. In the constructor for that class. 3. Right before you actually need to use the object. 4. Using instance initialization

Inheritance syntax You state new class in code before the opening brace of the class body, using the keyword extends followed by the name of the base class. When you do this, you automatically get all the fields and methods in the base class

Initializing the base class Since there are now two classes involved—the base class and the derived class—instead of just one, it can be a bit confusing to try to imagine the resulting object produced by a derived class. When you create an object of the derived class, it contains within it a sub-object of the base class

it’s essential that the base-class sub- object be initialized correctly, and there’s only one way to guarantee this: Perform the initialization in the constructor by calling the base-class constructor, which has all the appropriate knowledge and privileges to perform the base-class initialization. Java automatically inserts calls to the base-class constructor in the derived- class constructor

Constructors with arguments If your class doesn’t have default arguments, or if you want to call a base-class constructor that has an argument, you must explicitly write the calls to the base-class constructor using the super keyword and the appropriate argument list

Delegation A third relationship, which is not directly supported by Java, is called delegation. This is midway between inheritance and composition, because you place a member object in the class you’re building (like composition), but at the same time you expose all the methods from the member object in your new class (like inheritance)

Combining composition and inheritance It is very common to use composition and inheritance together. It’s rather amazing how cleanly the classes are separated. You don’t even need the source code for the methods in order to reuse the code. At most, you just import a package

Guaranteeing proper cleanup The practice is simply to forget about objects rather than to destroy them, allowing the garbage collector to reclaim the memory as necessary. If you want something cleaned up for a class, you must explicitly write a special method to do it, and make sure that the client programmer knows that they must call this method

Name hiding If a Java base class has a method name that’s overloaded several times, redefining that method name in the derived class will not hide any of the base-class versions. Java SE5 has added annotation, which is not a keyword but can be used as if it were. When you mean to override a method, you can choose to add this annotation and the compiler will produce an error message if you accidentally overload instead of overriding

Choosing composition vs. inheritance Both composition and inheritance allow you to place sub-objects inside your new class (composition explicitly does this—with inheritance it’s implicit). Composition is generally used when you want the features of an existing class inside your new class, but not its interface

When you inherit, you take an existing class and make a special version of it. In general, this means that you’re taking a general-purpose class and specializing it for a particular need. With a little thought, you’ll see that it would make no sense to compose a car using a vehicle object—a car doesn’t contain a vehicle, it is a vehicle. The is-a relationship is expressed with inheritance, and the has-a relationship is expressed with composition

Protected The protected keyword is a nod to pragmatism. It says “This is private as far as the class user is concerned, but available to anyone who inherits from this class or anyone else in the same package.” Although it’s possible to create protected fields, the best approach is to leave the fields private; you should always preserve your right to change the underlying implementation. You can then allow controlled access to inheritors of your class through protected methods

Upcasting The most important aspect of inheritance is the relationship expressed between the new class and the base class. This relationship can be summarized by saying, “The new class is a type of the existing class.”

As an example, consider a base class called Instrument that represents musical instruments, and a derived class called Wind. Because inheritance means that all of the methods in the base class are also available in the derived class, any message you can send to the base class can also be sent to the derived class. If the Instrument class has a play( ) method, so will Wind instruments. This means we can accurately say that a Wind object is also a type of Instrument

Why “upcasting”? The term is based on the way that class inheritance diagrams have traditionally been drawn: with the root at the top of the page, growing downward. Casting from a derived type to a base type moves up on the inheritance diagram, so it’s commonly referred to as upcasting

Upcasting is always safe because you’re going from a more specific type to a more general type. That is, the derived class is a superset of the base class. The only thing that can occur to the class interface during the upcast is that it can lose methods, not gain them

Composition vs. inheritance revisited In object-oriented programming, the most likely way that you’ll create and use code is by simply packaging data and methods together into a class, and using objects of that class. You’ll also use existing classes to build new classes with composition. Less frequently, you’ll use inheritance

So although inheritance gets a lot of emphasis while learning OOP, it doesn’t mean that you should use it everywhere you possibly can. On the contrary, you should use it sparingly, only when it’s clear that inheritance is useful

The final keyword Java’s final keyword has slightly different meanings depending on the context, but in general it says “This cannot be changed.” final data final methods final classes

final data Many programming languages have a way to tell the compiler that a piece of data is “constant.” A constant is useful for two reasons: 1. It can be a compile-time constant that won’t ever change. 2. It can be a value initialized at run time that you don’t want changed

In Java, these sorts of constants must be primitives and are expressed with the final keyword. A value must be given at the time of definition of such a constant. A field that is both static and final has only one piece of storage that cannot be changed

When final is used with object references rather than primitives, the meaning can be confusing. With a primitive, final makes the value a constant, but with an object reference, final makes the reference a constant

Blank finals Java allows the creation of blank finals, which are fields that are declared as final but are not given an initialization value. In all cases, the blank final must be initialized before it is used, and the compiler ensures this

However, blank finals provide much more flexibility in the use of the final keyword since, for example, a final field inside a class can now be different for each object, and yet it retains its immutable quality. You’re forced to perform assignments to finals either with an expression at the point of definition of the field or in every constructor. That way it’s guaranteed that the final field is always initialized before use

final arguments Java allows you to make arguments final by declaring them as such in the argument list. This means that inside the method you cannot change what the argument reference points to. This feature is primarily used to pass data to anonymous inner classes

final methods There are two reasons for final methods. The first is to put a “lock” on the method to prevent any inheriting class from changing its meaning. The second reason for final methods is efficiency. In earlier implementations of Java, if you made a method final, you allowed the compiler to turn any calls to that method into inline calls

In more recent version of Java, the virtual machine (in particular, the hotspot technologies) can detect these situations and optimize away the extra indirection, so its no longer necessary-in fact, it is now generally discouraged-to use final to try to help the optimizer

final and private Any private methods in a class are implicitly final. Because you can’t access a private method, you can’t override it

final classes When you say that an entire class is final (by preceding its definition with the final keyword), you state that you don’t want to inherit from this class or allow anyone else to do. In other words, for some reason the design of your class is such that there is never a need to make any changes, or for safety or security reasons you don’t want subclassing

final caution It can seem to be sensible to make a method final while you’re designing a class. In general, it’s difficult to anticipate how a class can be reused, especially a general-purpose class

Initialization and class loading The compiled code for each class exists in its own separate file. That file isn’t loaded until the code is needed. The point of first use is also where the static initialization takes place. All the static objects and the static code block will be initialized in textual order

Summary Both inheritance and composition allow you to create a new type from existing types. Composition reuses existing types as part of the underlying implementation of the new type, and inheritance reuses the interface. With Inheritance, the derived class has the base-class interface, so it can be upcast to the base, which is critical for polymorphism