Creating Classes from Other Classes Chapter 2. 2 Chapter Contents Composition Adapters Inheritance Invoking constructors from within constructors Private.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Inheritance Lakshmish Ramaswamy. Example A Rectangle class with area method A Circle class with area method Array containing references to circles & rectangles.
1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
CS 211 Inheritance AAA.
Inheritance Inheritance Reserved word protected Reserved word super
ITEC200 – Week03 Inheritance and Class Hierarchies.
Creating Classes from Other Classes Chapter 2 Slides by Steve Armstrong LeTourneau University Longview, TX  2007,  Prentice Hall.
© 2006 Pearson Addison-Wesley. All rights reserved2-1 Chapter 2 Object Oriented Programming & Software Engineering.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
Slides prepared by Rose Williams, Binghamton University Chapter 7 Inheritance.
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 7 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
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.
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.
© 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 using Java
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Viswanathan Inheritance and Polymorphism Course Lecture Slides 2 nd June 2010 “ We are.
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.
Programming With Java ICS201 University Of Ha’il1 Chapter 8 Polymorphism and Abstract Classes.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
CS200 Algorithms and Data StructuresColorado State University Part 4. Advanced Java Topics Instructor: Sangmi Pallickara
Inheritance in the Java programming language J. W. Rider.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
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.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
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…..
Chapter 8 Inheritance. 2  Review of class relationships  Uses – One class uses the services of another class, either by making objects of that class.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
CMSC 202 Inheritance II. Version 10/092 Inherited Constructors? An Employee constructor cannot be used to create HourlyEmployee objects. Why not? We must.
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,
Coming up: Inheritance
Creating Classes from Other Classes Appendix D © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance Objectives: Creating new classes from existing classes The protected modifier Creating class hierarchies Abstract classes Indirect visibility.
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.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Subclassing, pt. 2 Method overriding, virtual methods, abstract classes/methods COMP 401, Fall 2014 Lecture 9 9/16/2014.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
JAVA ACCESS MODIFIERS. Access Modifiers Access modifiers control which classes may use a feature. A classes features are: - The class itself - Its member.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Modern Programming Tools And Techniques-I
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.
Object Oriented Programming
Inheritance, Polymorphism, and Interfaces. Oh My
Extending Classes.
Java Programming Language
Inheritance, Polymorphism, and Interfaces. Oh My
Advanced Java Topics Chapter 9
Chapter 9 Carrano Chapter 10 Small Java
CIS 199 Final Review.
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

Creating Classes from Other Classes Chapter 2

2 Chapter Contents Composition Adapters Inheritance Invoking constructors from within constructors Private fields and methods of the base class Overriding, overloading methods Protected access Multiple inheritance Type compatibility and base classes The class Object Abstract classes and methods Polymorphism

3 Composition When a class has a data field that is an instance of another class Example – an object of type Student. Fig. 2-1 A Student object composed of other objects fig 2-1 A "has a" relationship

4 Student.java (1) // 2.2 public class Student { private Name fullName; private String id; // identification number public Student() { fullName = new Name(); id = ""; } // end default constructor public Student(Name studentName, String studentId) { fullName = studentName; id = studentId; } // end constructor public void setStudent(Name studentName, String studentId){ setName(studentName); // or fullName = studentName; setId(studentId); // or id = studentId; } // end setStudent

5 Student.java (2) public void setName(Name studentName) { fullName = studentName; } // end setName public Name getName() { return fullName; } // end getName public void setId(String studentId) { id = studentId; } // end setId public String getId() { return id; } // end getId public String toString() { return id + " " + fullName.toString(); } // end toString } // end Student

6 Generic Types public class WrapperClass { private T t; public WrapperClass (T t) { this.t = t; }... WrapperClass myInteger = new WrapperClass (new Integer(3)); WrapperClass myName = new WrapperClass (new Name(“Andy”));

7 Generic Types public class Pair(K,V) { private K key; private V value; public Pair(K k, V v ) { key = k; value = v; } public String toString () { return “(“+key+”,”+value+”)”; }

8 Adapters Use composition to write a new class Has an instance of an existing class as a data field Defines new methods needed for the new class Example: public class NickName { private Name nick; public NickName() { nick = new Name(); }// end default constructor public void setNickName(String nickName) { nick.setFirst(nickName); }// end setNickName public String getNickName() { return nick.getFirst(); }// end getNickName } // end NickName

9 Adapter (2) public class MonitoredArray { private ArrayList al = new ArrayList (10); private numberOfAccesses = 0; public MyArray () { } public void add(T t) { al.add(t); numberOfAccesses++; }... }

10 Inheritance A general or base class is first defined Then a more specialized class is defined by … Adding to details of the base class Revising details of the more general class Advantages Saves work Common properties and behaviors are define only once for all classes involved

11 Inheritance Fig. 2-2 A hierarchy of classes. An "is a" relationship

12 Inheritance Fig. 2-3 A hierarchy of student classes.

13 Calling the Base Class's Constructor Constructors usually initialize data fields In a derived class The constructor must call the base class constructor Can use the reserved word super as a name for the constructor of the base class When super is used, it must be the first action in the derived constructor definition Must not use the name of the constructor

14 Accessing Inherited Data Fields Private data field in base class Not accessible by name within definition of a method from another class – including a derived class Still they are inherited by the derived class Derived classes must use public methods of the base class Note that private methods in a base class are also unavailable to derived classes But usually not a problem – private methods are used only for utility duties within their class

15 Overriding Methods When a derived class defines a method with the same signature as in base class Same name Same return type Same number, types of parameters Objects of the derived class that invoke the method will use the definition from the derived class It is possible to use super in the derived class to call an overridden method of the base class public class AClass { public class BClass extends AClass { public void foo() {... } public void foo() { } super.foo(); // and then some more }

16 Overriding Methods Fig. 2-4 The method toString in CollegeStudent overrides the method toString in Student

17 Overriding Methods Multiple use of super Consider a class derived from a base … that itself is derived from a base class All three classes have a method with the same signature The overriding method in the lowest derived class cannot invoke the method in the base class's base class The construct super.super is illegal

18 Overloading a Method When the derived class method has The same name The same return type … but … Different number or type of parameters Then the derived class has available The derived class method … and The base class method with the same name Java distinguishes between the two methods due to the different parameters

19 Overloading a Method A programmer may wish to specify that a method definition cannot be overridden So that the behavior of the constructor will not be changed This is accomplished by use of the modifier final public final void whatever() {... }

20 Protected Access A method or data field modified by protected can be accessed by name only within Its own class definition Any class derived from that base class Any class within the same package org.cs2.pckg1 public class AClass { protected int x;... } public class BClass { // aClass.x visible here... }

21 Protected Access Fig. 2-5 Public, private, protected, and package access “package” access means no access is specified

22 Multiple Inheritance Some languages allow programmer to derive class C from classes A and B Java does not allow this A derived class can have only one base class Multiple inheritance can be approximated A derived class can have multiple interfaces Described in Chapter 3

23 Object Types of a Derived Class Given : Class CollegeStudent, Derived from class Student Then a CollegeStudent object is also a Student object In general … An object of a derived class is also an object of the base class

24 The Class Object Every class is a descendant of the class Object Object is the class that is the beginning of every chain of derived classes It is the ancestor of every other class Even those defined by the programmer Common Object methods that are often overridden: boolean equals(Object o) String toString()

25 The Class Object public class Object { boolean equals(Object o ) { if (this == o) return true; return false; } public class Name { boolean equals(Object o ) { if ( o == null || this.getClass() != o.getClass() ) return false; Name otherName = (Name) o; // cast return (this.first.equals(otherName.first) && this.last.equals(otherName.last)); } by default, Object just checks references but other Classes should check values.

26 Abstract Classes and Methods Some base classes are not intended to have objects of that type The objects will be of the derived classes Declare that base class to be abstract public abstract class Whatever {... } The designer often specifies methods of the abstract class without a body public abstract void doSomething(); This requires all derived classes to implement this method

27 Polymorphism When one method name in an instruction can cause different actions Happens according to the kinds of objects that invoke the methods Example The object still remembers it is of type UndergradStudent UndergradStudent ug = new UndergradStudent(...); Student s = ug; // s and ug are aliases s.displayAt(2); ug.displayAt(4); formal type actual type both call the overridden version of displayAt() in UndergradStudent

28 Polymorphism Which displayAt is called … Depends on the invoking object's place in the inheritance chain and is not determined by the type of the variable naming the object Fig. 2-6 The variable s is another name for an undergraduate object. starts at the bottom of the inheritance chain

29 Dynamic Binding The process that enables different objects to … Use different method actions For the same method name Objects know how they are supposed to act When an overridden method is used … The action is for the method defined in the class whose constructor created the object “Dynamic” means at run-time “Static” means at compile time “actual” type

30 Dynamic Binding Fig. 2-7 An object, not its name, determines its behavior.