2-1 Copyright (c) 1999 N. Afshartous Contents 1.Classes and Objects 2.Inheritance 3.Interfaces 4.Exceptions and Error Handling 5.Intro to Concurrency 6.Concurrency.

Slides:



Advertisements
Similar presentations
A subclass can add new private instance variables A subclass can add new public, private or static methods A subclass can override inherited methods A.
Advertisements

Inheritance. Many objects have a hierarchical relationship –Examples: zoo, car/vehicle, card game, airline reservation system Inheritance allows software.
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.
C12, Polymorphism “many forms” (greek: poly = many, morphos = form)
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
9. Inheritance 9.1 Subclasses 9.2 Polymorphism 9.3 Abstract Classes 9.4 Modifiers and Access 9.6 Object-Oriented Design with Use Cases and Scenarios.
ITEC200 – Week03 Inheritance and Class Hierarchies.
Inheritance The objectives of this chapter are: To explore the concept and implications of inheritance Polymorphism To define the syntax of inheritance.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance. In this chapter, we will cover: The concept of inheritance Extending classes Overriding superclass methods Working with superclasses that.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
1 Chapter 7 Inheritance, Polymorphism, and Scope.
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.
CPSC150 Abstract Classes and Interfaces Chapter 10.
Object Oriented Concepts in Java Objects Inheritance Encapsulation Polymorphism.
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.
Abstract Classes and Interfaces
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
Inheritance and Subclasses in Java CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
Inheritance using Java
Programming Languages and Paradigms Object-Oriented Programming.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Chapter 11 Inheritance and Composition. Chapter Objectives Learn about inheritance Learn about subclasses and superclasses Explore how to override the.
Specialization and Inheritance Chapter 8. 8 Specialization Specialized classes inherit the properties and methods of the parent or base class. A dog is.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
CSE 425: Data Types I Data and Data Types Data may be more abstract than their representation –E.g., integer (unbounded) vs. 64-bit int (bounded) A language.
Parameters… Classes Cont Mrs. C. Furman October 13, 2008.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Peyman Dodangeh Sharif University of Technology Fall 2014.
Inheritance and Access Control CS 162 (Summer 2009)
Inheritance Objectives: Creating new classes from existing classes The protected modifier Creating class hierarchies Abstract classes Indirect visibility.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
COMP Inheritance Basics Yi Hong June 09, 2015.
Coming up: Inheritance
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
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.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
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)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
SUBCLASSES - JAVA. The Purpose of Subclasses Class Farm String getOwner() void setOwner(String s) int getSize() void setSize(int s) Class DairyFarm String.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
BY:- TOPS Technologies
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
2-Oct-16 Basic Object-Oriented Concepts. 2 Concept: An object has behaviors In old style programming, you had: data, which was completely passive functions,
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Packages, Interfaces & Exception Handling
CSC 113 Tutorial QUIZ I.
Java Programming Language
Advanced Programming Behnam Hatami Fall 2017.
Inheritance Inheritance is a fundamental Object Oriented concept
Java Inheritance.
Inheritance.
Chapter 9 Carrano Chapter 10 Small Java
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

2-1 Copyright (c) 1999 N. Afshartous Contents 1.Classes and Objects 2.Inheritance 3.Interfaces 4.Exceptions and Error Handling 5.Intro to Concurrency 6.Concurrency in Java 7.Graphics and Animation 8.Applets

2-2 Copyright (c) 1999 N. Afshartous Chapter 2: Inheritance After this chapter you will be able to: -Extend existing classes using inheritance -Apply polymorphism -Understand static and dynamic binding -Use abstract classes

2-3 Copyright (c) 1999 N. Afshartous Inheritance Can define a class by inheriting the data attributes and methods of another object Inheritance is used to model the Is-A relationship An Employee Is-A Person class Person Name Age Location eat() sleep() class Employee SS# work() Is-A

2-4 Copyright (c) 1999 N. Afshartous Instantiation with Inheritance An Employee object has attributes defined in class Employee and Person Name: Fred Age: 40 Location: New York SS#:

2-5 Copyright (c) 1999 N. Afshartous Other Inheritance Examples Chair Lounge Chair Phone Rotary Phone Touch Tone Phone Cordless Phone Desk Chair Adjustable Desk Chair

2-6 Copyright (c) 1999 N. Afshartous Benefits Can use existing classes when defining new (more specialized) classes Well see later that polymorphism will: –facilitate software maintenance –allow us to write code that is generic

2-7 Copyright (c) 1999 N. Afshartous Other Languages Other OO languages with inheritance are: –C++ –Eiffel –SmallTalk –Ada95

2-8 Copyright (c) 1999 N. Afshartous Terms More generic class is called the superclass (parent) More specialized class is called the subclass (child) The set of Lounge chairs is a subset of the set of all Chairs Chair Lounge Chair Superclass (parent) Subclass (child)

2-9 Copyright (c) 1999 N. Afshartous Inheritance in Java Use keyword extends class Account { private int balance; private String owner; public Account (int b, String o) {...} public Account () {...} void deposit (int d) {... } void withdraw (int d) {... } public int getBalance () {...} public String getOwner () {...} } class BrokerageAccount extends Account { private int numShares; public BrokerageAccount () { numShares = 0; } }

2-10 Copyright (c) 1999 N. Afshartous Using A Brockerage Account Can access the public interface provided by class Account BrokerageAccount b = new BrokerageAccount(); System.out.println(“Balance = “ + b.getBalance()); b.deposit(100); System.out.println(“Balance = “ + b.getBalance()); Balance = 0 Balance = 100 Output balance: 100 owner: “nobody” numShares: 0

2-11 Copyright (c) 1999 N. Afshartous Inheritance and Private Cannot access the inherited private parts Compile-time error BrokerageAccount b = new BrokerageAccount(); System.out.println(“balance = “ + b.balance);

2-12 Copyright (c) 1999 N. Afshartous Inheritance and Constructors Problem: the constructor needs to initialize private parts of class Account Solution: use keyword super to invoke the superclass constructor class BrokerageAccount extends Account { private int numShares; public BrokerageAccount () { numShares = 0; } public BrockerageAccount (int balance, String owner) { this.balance = balance; this.owner = owner; }

2-13 Copyright (c) 1999 N. Afshartous Calling Superclass Constructor Call the superclass constructor which accepts int and String arguments Calling super will search the superclasses in the inheritance hiercy for a matching constructor class BrokerageAccount extends Account { private int numShares; public BrokerageAccount () { numShares = 0; } public BrockerageAccount (int balance, String owner) { super(balance, owner); }

2-14 Copyright (c) 1999 N. Afshartous More About Superclass Constructors In fact when an object is created some constructor for every class in the related hierchy must be called The default constructor of superclasses is invoked automatically unless super is used to call a non-default constructor

2-15 Copyright (c) 1999 N. Afshartous Question Compile-time error: can you see why ? class Account { private int balance; private String owner; public Account (int b, String o) {...} void deposit (int d) {... } void withdraw (int d) {... } public int getBalance () {...} public String getOwner () {...} } class BrokerageAccount extends Account { private int numShares; private int stockPrice; public BrokerageAccount () { numShares = 0; stockPrice = 0; } }

2-16 Copyright (c) 1999 N. Afshartous Answer No default constructor is provided by class Account class Account {... public Account (int b, String o) {...}... } class BrokerageAccount extends Account { private int numShares; private int stockPrice; public BrokerageAccount () { super(0,”nobody”); /*gets rid of error */ numShares = 0; stockPrice = 0; } }

2-17 Copyright (c) 1999 N. Afshartous Buying Stock class BrokerageAccount extends Account { private int numShares; private int stockPrice;... public void buy (int numShares) { int transactionAmount = numShares * stockPrice; if (getBalance() < transactionAmount) { System.out.println(“illegal transaction”); return; } this.numShares += numShares; withdraw(transactionAmount); } Buying involves withdrawing from the cash part of the Account

2-18 Copyright (c) 1999 N. Afshartous Balance of Brokerage Acct Balance is the sum of the cast Account and the value of the stock at a given price Can override the definition of getBalance in class Account with a definition in class BrokerageAccount Problem: need to call getBalance in the superclass to get the cash balance class BrokerageAccount extends Account { private int numShares;... public int getBalance () {...

2-19 Copyright (c) 1999 N. Afshartous Solution Use keyword super to call the superclass method class BrokerageAccount extends Account { private int numShares;... public int getBalance () { int cash = super.getBalance(); return cash + (numShares * stockPrice); } }

2-20 Copyright (c) 1999 N. Afshartous Complete Example class BrokerageAccount extends Account { private int numShares; public BrokerageAccount () { numShares = 0; } public BrockerageAccount (int balance, String owner) { super(balance, owner); public void buy (int numShares) { int transactionAmount = numShares * stockPrice; if (getBalance() < transactionAmount) { System.out.println(“illegal transaction”); return; } this.numShares += numShares; withdraw(transactionAmount); }...

2-21 Copyright (c) 1999 N. Afshartous Example continued public void buy (int numShares) { int transactionAmount = numShares * stockPrice; if (getBalance() < transactionAmount) { System.out.println(“illegal transaction”); return; } this.numShares += numShares; withdraw(transactionAmount); } public void sell (int numShares) { if (this.numShares < numShares) { System.out.println(“illegal translation”); return; } this.numShares -= numShares; deposit(numShares * stockPrice); }...

2-22 Copyright (c) 1999 N. Afshartous Example continued public int getBalance () { int cash = super.getBalance(); return cash + (numShares * stockPrice); } public void setStockPrice (int p) { stockPrice = p; } } /* end class BrokerageAccount */

2-23 Copyright (c) 1999 N. Afshartous Calling getBalance Can call getBalance using Account and BrokerageAccount objects Account a = new Account(1000,”fred”); System.out.println(“fred’s balance = “ + a.getBalance()); BrokerageAccount b = new BrokerageAccount(600,”mary"); b.buy(10, 50); System.out.println(“mary’s balance = “ + b.getBalance()); fred’s balance = 1000 mary’s balance = 600 Output

2-24 Copyright (c) 1999 N. Afshartous Subclass to Superclass Conversion A variable of type A can be bound to any object of type A or any of A’s subclasses This rule allows BrokerageAccount objects to be used in contexts where the Account type is specified Account b = new BrokerageAccount(600,”mary"); b ’s type object b will be bound to at run-time

2-25 Copyright (c) 1999 N. Afshartous Illegal Conversion The converse is not legal: A variable cannot be bound to any superclasses of it’s type Compile-time error Soon we’ll see that the legal conversion will allow us to incorporate polymorphism BrokerageAccount b = new Account(600,”mary");

2-26 Copyright (c) 1999 N. Afshartous Calling Deposit Method lookup: performed at run-time starting at the object’s class and then continuing with superclasses (if necessary) until a corresponding method definition is found Account a = new Account(1000,”fred”); a.deposit(100); /* calls Account.deposit() */ Account b = new BrokerageAccount(600,”mary"); b.deposit(100); /* no definition in BrokerageAccount, calls Account.deposit() */

2-27 Copyright (c) 1999 N. Afshartous Calling getBalance There are two definitions of getBalance The decision regarding which method to call is made at run-time based on the object (not the variables type) Account a = new Account(1000,”fred”); a.getBalance(); /* calls Account.getBalance() */ Account b = new BrokerageAccount(600,”mary"); b.getBalance(100);/* calls BrokerageAccount.getBalance()*/

2-28 Copyright (c) 1999 N. Afshartous Static vs Dynamic Binding Static binding: decides which method to call at compile-time based on type information Dynamic binding: decides which method to call at run-time based on the object used In Java (and SmallTalk, Eiffel) the default is dynamic binding In C++ the default is static binding

2-29 Copyright (c) 1999 N. Afshartous The Tradeoff Dynamic binding: -extra overhead (need to decide which method to call at run-time) +flexibility Static binding: -less flexibility (decision is fixed at compile-time) +efficiency

2-30 Copyright (c) 1999 N. Afshartous Question Which getBalance is going to be called ? void processAccount (Account a) {... balance = a.getBalance();... }

2-31 Copyright (c) 1999 N. Afshartous Answer Could be either! processAccount could be called multiple times with Account and BrokerageAccount objects the type of object will determine which getBalance gets called void processAccount (Account a) {... balance = a.getBalance();... }

2-32 Copyright (c) 1999 N. Afshartous End of Part I

2-33 Copyright (c) 1999 N. Afshartous It’s Exercise Time

2-34 Copyright (c) 1999 N. Afshartous Part II

2-35 Copyright (c) 1999 N. Afshartous Polymorphism English meaning of polymorhpism is: pertaining to multiple forms In the context of programing languages polymorphism means: –programs which operate on many types –data which have many types Two kinds of polymorphism: –OO polymorphism: constrained by a set of classes related by inheritance –Parametric polymorphism: type variables are used

2-36 Copyright (c) 1999 N. Afshartous Benefits of Polymorphism Genericity: Can write generic code that can be applied to different kinds of objects method processAccount can be applied to Account and BrokerageAccount objects The appropriate getBalance will be called void processAccount (Account a) {... balance = a.getBalance();... }

2-37 Copyright (c) 1999 N. Afshartous Benefits of Polymorphism Software maintenance: can extend the inheritance hierchy with new classes that can work with existing code Can call processAccount with an IRA_Account object without recompiling processAccount class IRA_Account extends Account { public int getBalance () {...} processAccount(new IRA_Account(200,”sam”))

2-38 Copyright (c) 1999 N. Afshartous Another Example class Car { private String type; public Car (String type) { this.type = type; } public void start () {.../* generic start */ } } class SportsCar extends Car { public SportsCar (String type) { super(type); } public void start () {.../* specific for SportsCar } } class Limo extends Car { public Limo (String type) { super(type); } public void start () {.../* specific for Limo */ } }

2-39 Copyright (c) 1999 N. Afshartous class Person { Car myCar = null; public Person (Car myCar) { this.myCar = myCar; } public void startCar () { myCar.start(); } }

2-40 Copyright (c) 1999 N. Afshartous Questions Person ed = new Person(new Car("chevy")); ed.startCar(); Person sally = new Person(new Limo("lincoln")); sally.startCar(); Calling startCar will indirectly call method start of which class ? How about now ?

2-41 Copyright (c) 1999 N. Afshartous Answers Person ed = new Person(new Car("chevy")); ed.startCar(); /* indirectly call Car.start() */ Person sally = new Person(new Limo("lincoln")); sally.startCar(); /* indirectly call LimoCar.start() */ class Person { Car myCar = null; public Person (Car myCar) { this.myCar = myCar; } public void startCar () { myCar.start(); } }

2-42 Copyright (c) 1999 N. Afshartous Adding MiniVans Person sally = new Person(new MiniVan("lincoln")); sally.startCar(); /* indirectly call MiniVan.start() */ class MiniVan extends Car { public MinVan (String type) { super(type); } public void start () {.../* specific for MiniVan*/ } } Can use MiniVans with class Person and the right start gets called

2-43 Copyright (c) 1999 N. Afshartous Summary We applied OO polymorphism to: –make class Person more generic (a person can have different types of cars) –facilitate software maintenance (added a new type of car which still works with class Person )

2-44 Copyright (c) 1999 N. Afshartous Inheritance and Access Using protected, a class can present a different interface for its subclasses –protected : access given to the class and its subclasses –public: access unrestricted –default (no keyword specified): access given to code inside the same package as the class

2-45 Copyright (c) 1999 N. Afshartous Using Protected ID can be accessed from subclasses of Account class Account { private int balance; private String owner; protected int ID; public Account (int b, String o, int ID) {...} void deposit (int d) {... } public int getBalance () {...} public String getOwner () {...} }

2-46 Copyright (c) 1999 N. Afshartous Direct Access From Subclasses Can access ID from BrokerageAccount class BrokerageAccount extends Account { private int numShares;... public void print () { System.out.println(“Brockerage Acct: “ + ID); } }

2-47 Copyright (c) 1999 N. Afshartous But Not From Outside Cannot Access ID outside of Account and BrokerageAccount Compile-time error Account a = new Account(1000,”fred”,402); System.out.println(“ID = “ + a.ID);

2-48 Copyright (c) 1999 N. Afshartous Abstract Classes Abstract classes: –cannot be instantiated –may contain the specifications of methods that must be defined by concrete subclasses Concrete classes are subclasses of abstract classes where all abstract method specifications have been defined (or have been defined by intermediate superclasses)

2-49 Copyright (c) 1999 N. Afshartous Declaring An Abstract Class Use keyword abstract Cannot create a Thing object Compile-time error abstract class Thing { } new Thing();

2-50 Copyright (c) 1999 N. Afshartous Abstract Methods Use abstract in the method specification An abstract class may contain both abstract and concrete methods abstract class Thing { String name; public Thing (String name) { this.name = name; } public String getName () { return name; } public abstract void print (); /* no body */ }

2-51 Copyright (c) 1999 N. Afshartous Concrete Class Can make a concrete class by: –extending Thing –implementing the print specification class Person extends Thing { String address; public Person (String name, String address) { super(name); this.address = address; } public void print () { System.out.println("Person: " + getName()); System.out.println("Address: " + address); }

2-52 Copyright (c) 1999 N. Afshartous Error Not defining print would produce a compile- time error Must either define print or define Person as abstract class Person extends Thing { String address; public Person (String name, String address) { super(name); this.address = address; } /* no definition of print */ }

2-53 Copyright (c) 1999 N. Afshartous Another Concrete Class Can have different concrete classes with different implementations of print class Car extends Thing { String model; public Car (String name, String model) { super(name); this.model = model; } public void print () { System.out.println("Car: " + getName()); System.out.println("Model: " + model); }

2-54 Copyright (c) 1999 N. Afshartous Reference “On Understanding Types, Data Abstraction and Polymorphism” by Luca Cardelli (Microsoft Research) available on the web at: – click on “Papers” link and then look for title