Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
CS 211 Inheritance AAA.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Inheritance Inheritance Reserved word protected Reserved word super
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
Encapsulation, Inheritance & Interfaces CSE 115 Spring 2006 February 27, March 1 & 3, 2006.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
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 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
CS 2511 Fall  Abstraction Abstract class Interfaces  Encapsulation Access Specifiers Data Hiding  Inheritance  Polymorphism.
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Slide 1 of 66. Lecture H Lecture H - Inheritance Unit H1 - Introduction to Inheritance.
CS221 - Computer Science II Polymorphism 1 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Intro to OOP with Java, C. Thomas Wu
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
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.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Computer Science and Engineering College of Engineering The Ohio State University Lot More Inheritance and Intro to Design Patterns Lecture 12.
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.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
What is inheritance? It is the ability to create a new class from an existing class.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Inheritance Objectives: Creating new classes from existing classes The protected modifier Creating class hierarchies Abstract classes Indirect visibility.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Coming up: Inheritance
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 7.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance Type/Subtype Relationship. Inheritance Idea: An object B of one type, termed child class, inherits from another object A of another type,
Inheritance and Polymorphism. Superclass and Subclass Inheritance defines a relationship between objects that share characteristics. It is a mechanism.
Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.
Classes, Interfaces and Packages
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Inheritance and Polymorphism
Java Inheritance 1/13/2015. Learning Objectives Understand how inheritance promotes software reusability Understand notions of superclasses and subclasses.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Lecture 12 Inheritance.
Inheritance and Polymorphism
Week 8 Lecture -3 Inheritance and Polymorphism
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Overloading and Constructors
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Chapter 11 Inheritance and Encapsulation and Polymorphism
CS 240 – Advanced Programming Concepts
Presentation transcript:

Application development with Java Lecture 21

Inheritance Subclasses Overriding Object class

Inheritance Idea Creation of new software from existing software components by adding only. You create objects of your class inside a new class. This is called composition. New class composed of objects of existing classes.

Superclass and Subclass Inheritance allows us to derive new classes from existing ones. The existing class is called superclass. The class that does the inheriting is said to be a subclass of the class from which it inherits. Sometimes the terms derived class and base class are used instead of subclass and superclass.

Inheritance Instances of the derived class inherits all the properties and functionality that are defined in base class. A derived class can add to the state and behavior that it inherits. It can also replace or modify inherited behavior.

Example Some examples of superclasses and subclasses:

Rules of Thumb Inheritance creates is-a relation. –if x is-a y -than x could extend y ColoredPoint is a Point. Everything that can be done with a Point object can be done with ColoredPoint object. ColoredPoint has all the functionality of a Point and some more.

Example

Another example Student - is a person who studies in the university or college. CS Student - is a person who studies computer science in the university or college. CS female Student – is a person who studies computer science in the university or college and it’s gender is female.

Student is a superclass of CS Student is a superclass CS female Student is a superclass CS female student in IDC. CS female student in IDC is a subclass of CS female Student is a subclass of CS Student is a subclass of Student. Another example

Creating a subclass A keyword extends used to show that the current class is a subclass of other class. Usually we try to extend the superclass data and methods by adding new features. Syntax: class class_name extends super_class_name { // additions to, and modifications of stuff inherited // from super class }

Example /** * A ColoredPoint class represents a Point object * with new data field color. */ public class ColoredPoint extends Point { private Color color; // … }

Example Subclass can also have new methods. public class ColoredPoint extends Point { private Color color; // new method void setColor(Color color) { this.color = color; } }

Subclass When you derive a class from a given base class: –The subclass inherits all the fields of the base class –It inherits all the methods of the base class Private fields and methods in the base class are inherited but they cannot be accessed directly from the code of the subclass. They are private and encapsulated in the base class itself.

Subclass methods Subclass can do one of the following with each inherited method: use the method as it is change it’s implementation – override Subclass can also have methods and data of his own, i.e. add methods.

Example

Constructors Constructors are not inherited. Constructors must be redefined. We often want to use the parent's constructor to set up the "parent's part" of the object. We do this by using the super keyword.

Example public class ColoredPoint extends Point { … // constructor public ColoredPoint(int x, int y,Color color) { super(x,y); this.color=color; } Constructor of the Point class

The super keyword The keyword super allows to refer to the parent (super) class. The super keyword can be used to access the method from the subclass. The first line of the constructor must invoke one of superclass constructors using super(..). If you do not call super(..) in the first line of the constructor the compiler automatically invoke the empty constructor of the superclass.

The default constructor The default constructor is empty constructor. If a given class does not have a constructor a default constructor is used by the compiler. If a subclass does not have a constructor then an empty constructor of superclass is invoked and an empty constructor of subclass itself.

Super(..) A subclass constructor needs to indicate which parent constructor to connect to. Example: super(x,y); // uses two integer constructor of Point super(); // uses default constructor

Super(..) and methods The major use of super is to override a method with a new method that extends the behavior of the inherited method. The new method can use super to call the inherited method, and it can include additional code to provide additional behavior. Syntax: super.method();

The super keyword public class ColoredPoint extends Point { … // ColoredPoint constructor s public ColoredPoint(int x, int y,Color color) { super(x,y);// constructor of the Point class this.color=color; // additional information } public ColoredPoint(int x, int y) { super(x,y);// constructor of the Point class } … }

Overriding Overriding means changing the implementation of the method while keeping it’s signature. Subclass can override a method implementation to provide a different version than parent. Subclass can add some information to parent version of the method. Subclass can completely re-define the parent’s method.

File RestrictedFile  File(String name)  isOpen()  open()  close()  getName()  RestrictedFile(String name, long key)  isLocked()  lock()  unlock(long key) Overriding Example: We want clients to be able to open a protected file only if it is unlocked

File Example /** * Part of a File implementation */ public class File { // The name of the file private String name; // true if the file is opened private boolean isOpen; /** * Construct a file with a given name. */ public File(String name) { this.name = name; }

File Example /** * Returns the name of the file. */ public String getName() { return name; } /** * Checks if the file is open. true iff the file is open */ public boolean isOpen() { return isOpen; } // other methods/variables... }

File Example /** * Opens the file. */ public void open() { // … other operations isOpen = true; } /** * Closes the file. */ public void close() { // … other operations isOpen = false; }

RestrictedFile Example /** * Represents a restricted file, which can be * opened only if it is unlocked. In order to * unlock the file a key is needed. */ public class RestrictedFile extends File { // Password for unlocking the file private long key; // The state of the file - locked/unlocked private boolean isLocked;

RestrictedFile Cont. // Constructs a new restricted file. // The key is used to unlock the file public RestrictedFile (String name, long key) { super(name); this.key = key; isLocked = true; } //Checks if the file is locked. public boolean isLocked() { return isLocked; }

RestrictedFile Cont. // Locks the file. public void lock() { isLocked = true; } // Unlock the file. // The file will be unlocked only // if the given key matches. public void unlock(long key) { if (this.key == key) { isLocked = false; }

RestrictedFile Cont. // Unlock the file. // The file will be unlocked only // if the given key matches. public void unlock(long key) { if (this.key == key) { isLocked = false; }

Locking? So far the implementation is useless if we do not change the implementation of open()!

RestrictedFile Overrides // Open the file. The file will be // opened only if it is unlocked. public void open() { if (!isLocked()) { super.open(); }

Overriding in RestrictedFile RestrictedFile inherits the interface of File, but changes the functionality of the method open(). We say that RestrictedFile overrides the method open(). Notice the call to super.open() - we invoke the method open() of the superclass on this object. (what if we just write “open()”?)

Rules of Overriding –When you derive a class B from a class A, the interface of class B will be a superset of that of class A (except for constructors). –You cannot remove a method from the interface by subclassing (why?). –However, class B can override some of the methods that it inherits and thus change their functionality. –The contract of a method states what is expected from an overriding implementation of the method.

Visibility modifiers Visibility modifiers determine which class members get inherited and which do not, which members are accessible and which are not. Any member (variable,method and constructor) can be declared with one of the 4 visibility modifiers: –public –private –protected

Visibility modifiers (revisited) public – accessible anywhere, inherited by all subclasses of its class. private – only code of the same class in which the member has been defined can access this member, inherited by subclasses of its class but can not be accessed directly from the code of the subclass. protected – accessible by any class in the same package as its class, inherited by all subclasses of its class. default – accessible by any class in the same package as its class, inherited by any class in the same package.

The final Modifier The final modifier can be used for classes, methods and variables, in each case it has a different meaning. A final variable can be initialized only once (constants). A final class can not have derived classes. A final method cannot be overridden.

Inheritance Several classes can be declared as subclasses of the same superclass. These subclasses share some structures and behaviors - the ones they inherit from their common superclass. The superclass expresses these shared structures and behaviors. Inheritance can also extend over several "generations" of classes.

Inheritance is Transitive In the diagram class E is a subclass of class D which is itself a subclass of class A. In this case, class E is considered to be a subclass of class A, even though it is not a direct subclass.

The Object Class Java defines the class java.lang.Object that is defined as a superclass for all classes. All classes directly or indirectly extend the Object class. If a class does not specify explicitly which class it is derived from, then it will be implicitly derived from class Object. All classes inherit Object’s methods.

Point ColoredPoint Object Hierarchy Diagram We can depict the relationship between this classes in the following diagram, that is called class hierarchy diagram.

File RestrictedFile Object Class Hierarchy Diagram: A Tree! IOvalTurtle IPoint

All Classes Extend Object The following two class definitions are equivalent: class SomeClass extends Object { // some code } class SomeClass { // some code }

Methods of Object Class The Object class defines a set of methods that are inherited by all classes. Some of them are: equals(Object o), getClass(), toString() toString() method that is used whenever we want to get a String representation of an object. When you define a new class, you can override the toString() method in order to have a suitable representation of the new type of objects as Strings.

toString() Method The toString() method is used whenever we want to get a String representation of an object. When you define a new class, you can override the toString() method in order to have a suitable representation of the new type of objects as Strings.

equals() Method The equals() method receives an Object as a parameter. Since all classes are derived from Object, every class “is an” Object. The implementation just checks if the two references ( this and obj ) are the same. You can override this method in order to fit your class logic (when are two points equal?, when are two URLs equal?)

Overloading Vs. Overriding –Overloading deals with multiple methods in the same class with the same name but different signatures. –Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature. –Overloading lets you define a similar operation in different ways for different data. –Overriding lets you define a similar operation in different ways for different object types.

Overriding toString() public class Point { private int x,y; public Point(int x, int y) {this.x=x; this.y=y; } public int getx() {return x;} public int gety() {return y;} public String toString() { return "(" + x + "," + y + ")"; } }

Overriding toString() public class ColoredPoint extends Point { private Color color; public ColoredPoint(int x, int y,Color color) { super(x,y); this.color=color; } void setColor(Color color) { this.color = color; } public String toString() { return "(" + getx() + "," + gety() + "," + color + ")"; }

Overriding toString() import java.awt.Color; class PrintingPointExample { public static void main(String[] args) { ColoredPoint p = new ColoredPoint(2,3,Color.red); System.out.println(p); }

Any Questions?