Inheritance, overloading and overriding



Similar documents
Java: overview by example

3 Pillars of Object-oriented Programming. Industrial Programming Systems Programming & Scripting. Extending the Example.

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

Chapter 13 - Inheritance

CS193j, Stanford Handout #10 OOP 3

Agenda. What is and Why Polymorphism? Examples of Polymorphism in Java programs 3 forms of Polymorphism

CS 111 Classes I 1. Software Organization View to this point:

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

D06 PROGRAMMING with JAVA

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

CS-XXX: Graduate Programming Languages. Lecture 25 Multiple Inheritance and Interfaces. Dan Grossman 2012

Java Interview Questions and Answers

AP Computer Science Java Subset

Java CPD (I) Frans Coenen Department of Computer Science

ICOM 4015: Advanced Programming

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

Yosemite National Park, California. CSE 114 Computer Science I Inheritance

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

CS170 Lab 11 Abstract Data Types & Objects

public void creditaccount(string accountnumber, float amount) { this.accounts.get(accountnumber).credit(amount); }

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

Programming Languages Featherweight Java David Walker

Software Engineering Techniques

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

Classes: Relationships Among Objects. Atul Prakash Background readings: Chapters 8-11 (Downey)

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Programming to Interfaces

JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.

Object-Oriented Programming in Java

Java Programming Language

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

More on Objects and Classes

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

LAB4 Making Classes and Objects

Abstract Classes. Suppose we want write a program that manipulates various types of bank accounts. An Account typically has following features;

History OOP languages Year Language 1967 Simula Smalltalk

java Features Version April 19, 2013 by Thorsten Kracht

Part I. Multiple Choice Questions (2 points each):

Polymorphism. Why use polymorphism Upcast revisited (and downcast) Static and dynamic type Dynamic binding. Polymorphism.

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

An Introduction To UML Class Diagrams Classes

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

Programming Language Concepts: Lecture Notes

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Moving from CS 61A Scheme to CS 61B Java

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

5. Advanced Object-Oriented Programming Language-Oriented Programming

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

AP Computer Science Static Methods, Strings, User Input

It has a parameter list Account(String n, double b) in the creation of an instance of this class.

Web Service Caching Using Command Cache

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

Tutorial on Writing Modular Programs in Scala

jmonitor: Java Runtime Event Specification and Monitoring Library

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

The Interface Concept

Introduction to Object-Oriented Programming

Understanding class definitions

Java Application Developer Certificate Program Competencies

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Grundlæggende Programmering IT-C, Forår Written exam in Introductory Programming

Design Patterns in Java

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Introduction to Java. CS 3: Computer Programming in Java

Unit Testing and JUnit

Sample CSE8A midterm Multiple Choice (circle one)

D06 PROGRAMMING with JAVA

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

CMSC 202H. ArrayList, Multidimensional Arrays

J a v a Quiz (Unit 3, Test 0 Practice)

Crash Course in Java

Object Oriented Software Design

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

CISC 181 Project 3 Designing Classes for Bank Accounts

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

Object Oriented Software Design

16.1 DataFlavor DataFlavor Methods. Variables

Description of Class Mutation Mutation Operators for Java

Programmation 2. Introduction à la programmation Java

15-214: Principles of Software Construction 8 th March 2012

Java Classes. GEEN163 Introduction to Computer Programming

Advanced Data Structures

Fundamentals of Java Programming

C:\Documents and Settings\Gijs\Desktop\src\client\Client.java dinsdag 3 november :50

objectives chapter Define classes that act like blueprints for new objects, made of variables and methods. Explain encapsulation and Java modifiers.

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

Génie Logiciel et Gestion de Projets. Object-Oriented Programming An introduction to Java

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below:

D06 PROGRAMMING with JAVA

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

Transcription:

Inheritance, overloading and overriding Recall with inheritance the behavior and data associated with the child classes are always an extension of the behavior and data associated with the parent class In a child class you can redefine a method's implementation (override) a method that is inherited by the parent, and the child class wants to change its behavior define new methods with the same method name but different arguments (overload) different tasks are performed by each method but they share the same method name 1

The Bank Account example Accounts must have current balance name of account holder a withdraw method a deposit method Current accounts have a maximum withdraw amount you cannot withdraw more than $200 in one transaction Savings accounts have a minimum balance that they need to maintain at all times. 2

The Bank Account example Shared behavior and data between Savings and Checking Data current balance name of account holder Behavior (method names and implementation) Both types of accounts have these methods and they behave the same accessors for common data deposit Behavior (method names without behavior) withdraw Both types of accounts have these methods display but each method behaves differently in each account type 3

The Bank Account example Account is a generalized idea What actually exists in the banking model are savings and checking accounts. both are accounts with specialized operations on them. you can refer to them as accounts but you are using them according what a savings and/or a checking account can do. Generalized ideas (i.e. Account) can be directly mapped in java as abstract classes interfaces. 4

The Bank Account with abstract classes Account double balance String name +getbalance():double +getname():string +setname(string):void +setbalance(double):void +deposit(double):boolean +withdraw(double):boolean +display() abstract class abstract methods Abstract classes cannot be instantiated there is no constructor! Abstract methods must be implemented by subclasses of Account there is no body for withdraw and display inside Account 5

The Bank Account with abstract classes Account double balance String name +getbalance():double +getname():string +setname(string):void +setbalance(double):void +deposit(double):boolean +withdraw(double):boolean +display() Checking Savings double minimumbalance +getminbal():double +setminbal(double):void 6

The Bank Account with abstract classes abstract public class Account { double balance; String name; Account double balance String name +getbalance():double +getname():string +setname(string):void +setbalance(double):void +deposit(double):boolean +withdraw(double):boolean +display() public double getbalance(){ return balance; public void setbalance(double val){ balance = val; public String getname(){ return name; public void setname(string aname){ name = aname; public boolean deposit(double amount){ balance = balance + amount; return true; abstract public boolean withdraw(double amount); abstract public void display(); 7

The Bank Account with abstract classes Account double balance String name +getbalance():double +getname():string +setname(string):void +setbalance(double):void +deposit(double):boolean +withdraw(double):boolean +display() Checking public class Checking extends Account{ Checking(String name, double amount){ this.name = name; if (amount > 0){ this.balance = amount; else { // error reporting code omitted this.balance = 0; public boolean withdraw(double amount){ if (amount > 0 && amount <= balance) { balance = balance - amount; return true; else if ( amount > balance){ // error reporting code omitted return false; else { // error reporting code omitted return false; public void display(){ System.out.println(" ****** Current Account Details ****** "); System.out.println(" Name: "+ this.getname()); System.out.println(" Current Balance: "+ this.getbalance()); System.out.println("\t\t\t\t ****** Current Account Details ****** "); 8

The Bank Account with abstract classes Account double balance String name +getbalance():double +getname():string +setname(string):void +setbalance(double):void +deposit(double):boolean +withdraw(double):boolean +display() Savings double minimumbalance +getminbal():double +setminbal(double):void public class Savings extends Account{ double minimumbalance; Savings(String name, double amount, double minbalance){ this.name = name; if (amount > 0){ this.balance = amount; else { // error reporting code omitted this.balance = 0; if (minbalance > 0){ this.minimumbalance = minbalance; else { // error reporting code omitted this.minimumbalance = 0; public void setminbal(double newbal){ minimumbalance = newbal; public double getminbal(){ return minimumbalance; public boolean withdraw(double amount){ //code omitted public void display(){ //code omitted 9

Overloading the constructor public class Savings extends Account{ double minimumbalance; Distinguish the constructor by number of arguments and types for each argument. Savings(String name, double amount, double minbalance){ this.name = name; if (amount > 0){ this.balance = amount; else { // error reporting code omitted this.balance = 0; if (minbalance > 0){ this.minimumbalance = minbalance; else { // error reporting code omitted this.minimumbalance = 0; Savings(String name, double amount){ this.name = name; if (amount > 0){ this.balance = amount; else { this.balance = 0; this.minimumbalance = 0; 10

Overloading the constructor public class Savings extends Account{ double minimumbalance; public class Main{ public static void main(string[] args){ Savings mysavings = new Savings( John,100.00,50.00); Savings anothersavings = new Savings( Mary,200.00); Savings(String name, double amount, double minbalance){ this.name = name; if (amount > 0){ this.balance = amount; else { // error reporting code omitted this.balance = 0; if (minbalance > 0){ this.minimumbalance = minbalance; else { // error reporting code omitted this.minimumbalance = 0; Savings(String name, double amount){ this.name = name; if (amount > 0){ this.balance = amount; else { this.balance = 0; this.minimumbalance = 0; 11

Overloading a method public class Savings extends Account{ double minimumbalance; public class Main{ public static void main(string[] args){ Savings mysavings = new Savings( John,100.00,50.00); Savings anothersavings = new Savings( Mary,200.00); mysavings.display(); mysavings.display( Today ); public void display(){ System.out.println("\n ****** Savings Account Details ****** "); System.out.println(" Name: "+ this.getname()); System.out.println(" Current Balance: "+ this.getbalance()); System.out.println(" Minimum Balance: "+ this.getminbal()); System.out.println("\t\t\t\t ****** Savings Account Details ******\n "); public void display(string date){ System.out.println(date+ your balance is +this.getbalance()); 12

Bank account with interfaces only! Interfaces in java define sets of operations that the type must implement. <<IAccount>> Checking double balance String name +getbalance():double +getname():string +setname(string):void +setbalance(double):void +deposit(double):boolean +withdraw(double):boolean +display() Savings double minimumbalance double balance String name +getminbal():double +setminbal(double):void 13

Bank account with interfaces only! <<IAccount>> +getbalance():double +getname():string +setname(string):void +setbalance(double):void +deposit(double):boolean +withdraw(double):boolean +display() interface IAccount { public double getbalance(); public String getname(); public void setname(string aname); public void setbalance(double amount); public boolean deposit(double amount); public boolean withdraw(double amount); public void display(); There is no implementation inside interfaces! 14

Bank account with interfaces only! Savings double minimumbalance double balance String name +getminbal():double +setminbal(double):void public class Savings implements IAccount{ double minimumbalance; double balance; String name; // Same as Slide 7 public double getbalance(){ public void setbalance(double val){ public String getname(){ public void setname(string aname){ public boolean deposit(double amount){ // Same as Slide 9 Savings(String name, double amount){ Savings(String name, double amount, double minbalance){ public void setminbal(double newbal){ public double getminbal(){ public boolean withdraw(double amount){ public void display(){ 15

Bank account with interfaces only! Checking double balance String name public class Checking implements IAccount{ double minimumbalance; double balance; String name; // Same as Slide 7 public double getbalance(){ public void setbalance(double val){ public String getname(){ public void setname(string aname){ public boolean deposit(double amount){ // Same as Slide 8 public boolean withdraw(double amount){ public void display(){ 16

Interfaces or Abstract classes Java allows you to implement as many interfaces as you like you can only extend one abstract class not more! Abstract classes can also contain state (instance variables) and implemented methods interfaces cannot have instance variables (they can have static variables) and cannot have implementations for methods 17

Interfaces or Abstract classes (cont) Both define a type with abstract classes you can also share implementation and enforce method signatures to be implemented later with interfaces you can only enforce method signatures that need to be implemented later A class can implement multiple interfaces but extend only one class (concrete or abstract) 18

Types Revisited In Java each interface defines a type. Interface extension and implementation as subtype relationships A subtype relation in Java is: if class C 1 extends class C 2 then C 1 is a subtype of C 2 if interface I 1 extends I then I 1 is a subtype of I if class C implements interface I then C is a subtype of I for every interface I, I is a subtype of Object for every type T, T[ ] is a subtype of Object if T 1 is a subtype of T 2 then T 1 [ ] is a subtype of T 2 [ ] 19

Upcasting Operation that changes the runtime type of an instance to one of its supertypes (i.e. move up the hierarchy) force an instance that is of type Savings Account to be viewed as of type Account. public class Main{ public static void main(string[] args){ Savings mysavings = new Savings( John,100.00,50.00); Savings anothersavings = new Savings( Mary,200.00); Checking caccount = new Checking( Michael, 89.00); mysavings.display(); mysavings.display( Today ); Force mysavings to be used as of type Account Account oneac = (Account) mysavings; Account secondac= (Account) caccount; Account[] allaccounts = new Account[10]; allaccounts[0] = oneac; allaccounts[1] = secondac; 20

Downcasting Operation that changes the runtime type of an instance to one of its supertypes (i.e. move down the hierarchy) public class Main{ force an instance that is of type Account to be viewed as of type Savings Account. Force the first element of the array that is of type Account to be used as of type Savings public static void main(string[] args){ Savings mysavings = new Savings( John,100.00,50.00); Savings anothersavings = new Savings( Mary,200.00); Checking caccount = new Checking( Michael, 89.00); mysavings.display(); mysavings.display( Today ); Account oneac = (Account) mysavings; Account secondac= (Account) caccount; Account[] allaccounts = new Account[10]; allaccounts[0] = oneac; allaccounts[1] = secondac; Savings saveacc = (Savings) allaccounts[0]; Savings saveacc2 = (Savings) allaccounts[1]; The second element in the list is an instance of Checking Account, stored as of type Account. Casting it to Savings is wrong! 21