Extending classes with inheritance Learning objectives By the end of this lecture you should be able to: explain the term inheritance; design inheritance.

Slides:



Advertisements
Similar presentations
1.A computer game is an example of A.system software; B.a compiler; C.application software; D.hardware; E.none of the above. 2.JVM stands for: A.Java Virtual.
Advertisements

Classes and objects Learning objectives By the end of this lecture you should be able to: explain the meaning of the term object-oriented; explain the.
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
MSc IT Programming Methodology (2). number name number.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Inheritance and.
1 Inheritance Chapter 9. 2 Module Outcomes To develop a subclass from a superclass through inheritance To invoke the superclass ’ s constructors and methods.
Implementing Classes Learning objectives By the end of this lecture you should be able to: design classes using the notation of the Unified Modeling Language.
SD1042 Introduction to Software Development. Extending classes with inheritance Robot DancingRobot Sharing attributes and methods.
09 Inheritance. 2 Contents Defining Inheritance Relationships of Inheritance Rules of Inheritance super and this references super() and this() methods.
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance CT Introduction 2  Inheritance  Software reusability  Create new class from existing class  Absorb existing class’s data and behaviors.
© The McGraw-Hill Companies, 2006 Chapter 8 Extending classes with inheritance.
Designing Classes Chapter 3. 2 Chapter Contents Encapsulation Specifying Methods Java Interfaces Writing an Interface Implementing an Interface An Interface.
Arrays Horstmann, Chapter 8. arrays Fintan Array of chars For example, a String variable contains an array of characters: An array is a data structure.
Java boot camp1 Subclasses Concepts: The subclass and inheritance: subclass B of class A inherits fields and methods from A. A is a superclass of B. Keyword.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
MSc IT Programming Methodology (2). MODULE TEAM Dr Aaron Kans Dr Sin Wee Lee.
Java Unit 9: Arrays Declaring and Processing Arrays.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
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.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
1 Chapter 10 Object-Oriented Thinking. 2 Class Abstraction and Encapsulation Class abstraction means to separate class implementation details from the.
Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types.
MSc IT Programming Methodology (2). Oblong EasyScanner BankAccount.
Programming With Java ICS Chapter 8 Polymorphism.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.
CET203 SOFTWARE DEVELOPMENT Session 1A Revision of Classes.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
An Introduction to Java – Part 1 Dylan Boltz. What is Java?  An object-oriented programming language  Developed and released by Sun in 1995  Designed.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
Ch 23 Java in context Learning objectives By the end of this lecture you should be able to:  explain the difference between a reference and a pointer;
Topic 4 Inheritance.
CMSC 202 Inheritance I Class Reuse with Inheritance.
Java 1.5 The New Java Mike Orsega Central Carolina CC.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Inheritance and Design CSIS 3701: Advanced Object Oriented Programming.
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
1 IM103 Wk 7 (C&K ch14, p323) Abstraction, inheritance and interfaces Learning objectives By the end of this lecture you should be able to:  explain the.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
Inheritance CT Introduction Inheritance Software reusability Create new class from existing class Absorb existing class’s data and behaviors Enhance.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Classes CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Exam 2 EXAM 2 Thursday!!! 25% of Final Grade Know: loops, switch/case Files Input failure (e.g. scan.hasNextInt())
Inheritance CT Introduction Inheritance Software reusability Create new class from existing class Absorb existing class’s data and behaviors Enhance.
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Modern Programming Tools And Techniques-I
Data Structures and Algorithms revision
Lecture 12 Inheritance.
Building Java Programs
Computer Programming Methodology Input and While Loop
Programming Language Concepts (CIS 635)
An Introduction to Java – Part I
Classes Variables That Are Not of a Built-in Type Are Objects
null, true, and false are also reserved.
An Introduction to Java – Part I, language basics
Inheritance CT1513.
CIS 199 Final Review.
Building Java Programs
Presentation transcript:

Extending classes with inheritance Learning objectives By the end of this lecture you should be able to: explain the term inheritance; design inheritance structures using UML notation; implement inheritance relationships in Java; distinguish between method overriding and method overloading; explain the term type cast and implement this in Java; explain the use of the abstract modifier and the final modifier, when applied to both classes and methods; describe the way in which all Java classes are derived from the Object class.

Software Reuse Employee Full-time Employee Part-time Employee BankAccount Interest Account

Defining inheritance Inheritance is the sharing of attributes and methods among classes; The inheritance relationship is also often referred to as an is-a-kind-of relationship; PartTimeEmployee is a kind of Employee InterestAccount is a kind of BankAccount Car is a kind of Vehicle Monitor i s not a kind of Computer

UML notation for inheritance Employee number : String name : String Employee(String, String) setName(String) getNumber() : String getName() : String PartTimeEmployee hourlyPay : double PartTimeEmployee(String, String, double) setHourlyPay(double) getHourlyPay() :double calculateWeeklyPay(int) :double superclasssubclass base classderived class

public class Employee { private String number; private String name; public Employee(String numberIn, String nameIn) { number = numberIn; name = nameIn; } public void setName(String nameIn) { name = nameIn; } public String getNumber() { return number; } public String getName() { return name; } }

public class PartTimeEmployee extends Employee { private double hourlyPay; public PartTimeEmployee(String numberIn, String nameIn, double hourlyPayIn) { super(numberIn, nameIn); hourlyPay = hourlyPayIn; } public double getHourlyPay() { return hourlyPay; } public void setHourlyPay(double hourlyPayIn) { hourlyPay = hourlyPayIn; } public double calculateWeeklyPay(int noOfHoursIn) { return noOfHoursIn * hourlyPay; } }

public class PartTimeEmployeeTester { public static void main(String[] args) { String number, name; double pay; int hours; PartTimeEmployee emp; System.out.print("Employee Number? "); number = EasyScanner.nextString(); System.out.print("Employee's Name? "); name = EasyScanner.nextString(); System.out.print("Hourly Pay? "); pay = EasyScanner.nextDouble(); System.out.print("Hours worked this week? "); hours = EasyScanner.nextInt(); emp = new PartTimeEmployee(number, name, pay); System.out.println(); System.out.println(emp.getName()); System.out.println(emp.getNumber()); System.out.println(emp.calculateWeeklyPay(hours)); } }

public class PartTimeEmployeeTester { public static void main(String[] args) { String number, name; double pay; int hours; PartTimeEmployee emp; System.out.print("Employee Number? "); number = EasyScanner.nextString(); System.out.print("Employee's Name? "); name = EasyScanner.nextString(); System.out.print("Hourly Pay? "); pay = EasyScanner.nextDouble(); System.out.print("Hours worked this week? "); hours = EasyScanner.nextInt(); emp = new PartTimeEmployee(number, name, pay); System.out.println(); System.out.println(emp.getName()); System.out.println(emp.getNumber()); System.out.println(emp.calculateWeeklyPay(hours)); } RUN Employee Number? Walter Wallcarpeting A Employee's Name? Hourly Pay? Hours worked this week? A Walter Wallcarpeting

Extending the Oblong class Oblong myOblong= new Oblong(6.5, 9.2); ********* ********* ********* ********* ********* *********

ExtendedOblong symbol : char ExtendedOblong(double, double, char) setSymbol(char) draw() : String Oblong length : double height : double Oblong(double, double) setLength(double) setHeight(double) getLength() : double getHeight() : double calculateArea() : double calculatePerimeter() : double

public class ExtendedOblong extends Oblong { private char symbol; public ExtendedOblong (double lengthIn, double heightIn, char symbolIn) { super(lengthIn, heightIn); symbol = symbolIn; } public void setSymbol(char symbolIn) { symbol = symbolIn; } public String draw() { // code to produce String goes here } }

The new-line character **** **** **** ************ <NEW LINE><NEW LINE> ‘\n’ for (int j = 1; j <= length; j++) { s = s + symbol; } s = s + '\n'; for (int i = 1; i <= height; i++) { } <NEW LINE>

public String draw() { String s ; int length, height; length = getLength(); height = getHeight(); for (int i = 1; i <= height; i++) { for (int j = 1; j <= length; j++) { s = s + symbol; } s = s + '\n'; } return s; } } = “ “;= new String(); (int)

public class ExtendedOblongTester { public static void main(String[] args) { ExtendedOblong extOblong = new ExtendedOblong(10,5,'*'); System.out.println(extOblong.draw()); extOblong.setSymbol('+'); System.out.println(extOblong.draw()); } } RUN ********** ********** ********** ********** **********

Method overriding Customer name : String totalMoneyPaid : double totalGoodsReceived : double Customer(String) getName() : String getTotalMoneyPaid() : double getTotalGoodsReceived() : double calculateBalance() : double recordPayment(double) dispatchGoods(double) : boolean GoldCustomer creditLimit : double GoldCustomer(String, double) getCreditLimit() : double setCreditLimit(double) dispatchGoods(double) : boolean

public class Customer { protected String name; protected double totalMoneyPaid; protected double totalGoodsReceived; public Customer(String nameIn) { name = nameIn; totalMoneyPaid = 0; totalGoodsReceived = 0; } // more methods go here }

public String getName() { return name; } public double getTotalMoneyPaid() { return totalMoneyPaid; } public double getTotalGoodsReceived() { return totalGoodsReceived; } public double calculateBalance() { return totalMoneyPaid - totalGoodsReceived; }

public void recordPayment(double paymentIn) { totalMoneyPaid = totalMoneyPaid + paymentIn; } public boolean dispatchGoods(double goodsIn) { if(calculateBalance() >= goodsIn) { totalGoodsReceived = totalGoodsReceived + goodsIn; return true; } else { return false; } }

public class GoldCustomer extends Customer { private double creditLimit; public GoldCustomer(String nameIn, double limitIn) { super(nameIn); creditLimit = limitIn; } public void setCreditLimit(double limitIn) { creditLimit = limitIn; } public double getCreditLimit() { return creditLimit; } // code for dispatchGoods }

public boolean dispatchGoods(double goodsIn) { if((calculateBalance() + creditLimit) >= goodsIn) { totalGoodsReceived = totalGoodsReceived + goodsIn; return true; } else { return false; } }

Customer firstCustomer = new Customer("Jones"); GoldCustomer secondCustomer = new GoldCustomer("Cohen", 500); // more code here firstCustomer.dispatchGoods(98.76); secondCustomer.dispatchGoods(32.44); Effect of overriding methods

Abstract classes and methods draw() abstract draw() draw() ShapeCircleTriangle abstract Shape

Employee number : String name : String Employee(String, String) setName(String) getNumber() : String getName() : String getStatus() : String FullTimeEmployee annualSalary : double FullTimeEmployee(String, String, double) setAnnualSalary(double) getAnnualSalary() : double calculateMonthlyPay () : double getStatus() : String PartTimeEmployee hourlyPay : double PartTimeEmployee(String,String, double) setHourlyPay(double) getHourlyPay() : double calculateWeeklyPay(int) : double getStatus() : String An Example

public abstract class Employee { // attributes as before // methods as before abstract public String getStatus(); }

public class PartTimeEmployee extends Employee { // code as before public String getStatus() { return "Part-Time"; } }

public class FullTimeEmployee extends Employee { private double annualSalary; public FullTimeEmployee(String numberIn, String nameIn, double salaryIn) { super(numberIn,nameIn); annualSalary = salaryIn; } // other methods here }

public void setAnnualSalary(double salaryIn) { annualSalary = salaryIn; } public double getAnnualSalary() { return annualSalary; } public double calculateMonthlyPay() { return annualSalary/12; } public String getStatus() { return "Full-Time"; }

Inheritance and Types Employee e ; PartTimeEmployee p ; FullTimeEmployee f ; getStatus() abstract getStatus() getStatus() Employee PartTimeEmployee FullTimeEmployee public class StatusTester { public static void tester(Employee employeeIn) { System.out.println(employeeIn.getStatus()); } }

public class RunStatusTester { public static void main(String[] args) { FullTimeEmployee fte = new FullTimeEmployee("100", "Patel", 30000); PartTimeEmployee pte = new PartTimeEmployee("101", "Jones", 12); StatusTester.tester(fte); StatusTester.tester(pte); } } RUN Full-Time Part-Time

The final modifier final double PI = ; public final class SomeClass { // code goes here } public final void someMethod() { // code goes here } SomeClass someMethod() AnotherClass someMethod() final SomeClass final someMethod()

The Object class Employee PartTimeEmployee FullTimeEmployee String BankAccount Object

Generic Arrays private BankAccount[] list; This array can only hold BankAccount objects private Employee[] list; This array can only hold Employee objects private Object[] list; This array can only hold any type of objects Bank EmployeeList ObjectList

Generic Methods - add public boolean add( BankAccount itemIn) { if (!isFull()) { list[total] = itemIn; total++; return true; } else { return false; } } Object objectList.add( new BankAccount(“007”, “James Bond”) ) ;

Generic Methods - getItem public BankAccount getItem(int positionIn) { if(positionIn < 1 || positionIn > total) { return null; } else { return list[positionIn - 1]; } } Object BankAccount myAccount = objectList.getItem(3); System.out.println(myAccount.getBalance()); (BankAccount) objectList.getItem(3);

Wrapper classes QHow could you use an array of Objects to store a simple type such as an int or a char - or to pass such a type to a method that expects an Object? AUse a wrapper class. Integer hidden int Integer(int) getValue():int Character hidden char Character(char) getValue():char Double hidden double Double(double) getValue():double objectList.add( new Integer( 37)) ;

Autoboxing Object[] anArray = new Object[20]; anArray[0] = new Integer(37); Java 5.0 allows us to make use of a technique known as autoboxing: anArray[0] = 37;

Unboxing Integer intObject = (Integer) anArray[0]; int x = intObject.getValue(); Java 5.0 allows us to make use of a technique known as unboxing: int x = (Integer) anArray[0];

A mixed list Third item Second item First item Part-time employee Full-time employee Full-time employee Employee[] employeeList = new Employee[3];

public class MixedListTester { public static void main(String[] args) { Employee[] employeeList = new Employee[3]; String num, name; double pay; char status; for(int i = 0; i < employeeList.length; i++) { System.out.print("Enter the employee number: "); num = EasyScanner.nextString(); System.out.print("Enter the employee's name: "); name = EasyScanner.nextString(); System.out.print("<F>ull-time or <P>art-time? "); status = EasyScanner.nextChar(); // more code here }

if(status == 'f' || status == 'F') { System.out.print("Enter the annual salary: "); } else { System.out.print("Enter the hourly pay: "); } pay = EasyScanner.nextDouble(); if(status == 'f' || status == 'F') { employeeList[i] = new FullTimeEmployee(num, name, pay); } else { employeeList[i] = new PartTimeEmployee(num, name, pay); } System.out.println(); } // end of loop

for(Employee item : employeeList) { System.out.println("Employee number: " + item.getNumber()); System.out.println("Employee name: " + item.getName()); System.out.println("Status: " + item.getStatus()); System.out.println(); }

public class MixedListTester { public static void main(String[] args) { Employee[] employeeList = new Employee[3]; // declare local variables to hold values entered by user String num, name; double pay; char status; for(int i = 0; i < employeeList.length; i++) { System.out.print("Enter the employee number: "); num = EasyScanner.nextString(); System.out.print("Enter the employee's name: "); name = EasyScanner.nextString(); System.out.print(" ull-time or art-time? "); status = EasyScanner.nextChar(); if(status == 'f' || status == 'F') { System.out.print("Enter the annual salary: "); } else { System.out.print("Enter the hourly pay: "); } pay = EasyScanner.nextDouble(); if(status == 'f' || status == 'F') { employeeList[i] = new FullTimeEmployee(num, name, pay); } else { employeeList[i] = new PartTimeEmployee(num, name, pay); } System.out.println(); } for(Employee item : employeeList) { System.out.println("Employee number: " + item.getNumber()); System.out.println("Employee name: " + item.getName()); System.out.println("Status: " + item.getStatus()); System.out.println(); } RUN Enter the employee number: 1 Enter the employee's name: Jones <F>ull-time or <P>art-time? f Enter the annual salary: Enter the employee number: 2 Enter the employee's name: Agdeboye <F>ull-time or <P>art-time? f Enter the annual salary: Enter the employee number: 3 Enter the employee's name: Sharma <F>ull-time or <P>art-time? p Enter the hourly pay: 15

Employee number: 1 Employee name: Jones Status: Full-Time Employee number: 2 Employee name: Agdeboye Status: Full-Time Employee number: 3 Employee name: Sharma Status: Part-Time