Introduction to Computer Science Inheritance Classes and Methods: Static Methods and Variables Unit 11.

Slides:



Advertisements
Similar presentations
Escape Sequences \n newline \t tab \b backspace \r carriage return
Advertisements

Lecture 5: Interfaces.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
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.
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
CSCI 1100/1202 April 3, Testing A program should be executed multiple times with various input in an attempt to find errors Debugging is the process.
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
Java Inheritance. What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these.
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Java Programming, Second Edition Chapter Four Advanced Object Concepts.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
CMSC 202 Inheritance II. Version 10/102 Inherited Constructors? An Employee constructor cannot be used to create HourlyEmployee objects. Why not? We must.
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.
The Java Programming Language
CSC 142 Computer Science II Zhen Jiang West Chester University
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
Centre for Computer Technology ICT214 Object Oriented Design and Programming Week 02 – Classes, Objects, Instances Richard Salomon and Umesh Patel Centre.
10-Nov-15 Java Object Oriented Programming What is it?
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Programming in Java CSCI-2220 Object Oriented Programming.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
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 with Java 03 - Introduction to Classes and Objects.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
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.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Chapter 5 Classes and Methods II Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
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.
CMSC 202 Polymorphism. 10/20102 Topics Binding (early and late) Upcasting and downcasting Extensibility The final modifier with  methods  classes.
Java Programming, Second Edition Chapter Three Using Methods, Classes, and Objects.
Chapter 7 Classes and Methods III: Static Methods and Variables Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition)
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
 The word static is used to declare either a ________ variable or method.  Why do we use statics?  What is Polymorphism? class In general, we use a.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Topic: Classes and Objects
Inheritance ITI1121 Nour El Kadri.
Introduction to Computer Science / Procedural – 67130
Chapter 3: Using Methods, Classes, and Objects
Computer Science II Exam 1 Review.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
CSC 143 Inheritance.
Inheritance 2nd Lecture
Object Oriented Programming (OOP) LAB # 8
Chapter 6 Methods: A Deeper Look
Java Programming Language
Week 6 Object-Oriented Programming (2): Polymorphism
Object Oriented Programming (OOP) LAB # 5
Inheritance 2nd Lecture
Inheritance 2nd Lecture
Java Inheritance.
Java Programming Language
Chapter 8 Inheritance Part 2.
Visibilities and Static-ness
CMSC 202 Inheritance II.
Presentation transcript:

Introduction to Computer Science Inheritance Classes and Methods: Static Methods and Variables Unit 11

11- 2 Inheritance We've seen inheritance first in the robot world Inheritance allows a programmer to customize an existing class to a new application, by defining a new class that inherits from the first, but adds or redefines instance methods as necessary

11- 3 From the Robot World: Class Hierarchy (showing Attributes, not Methods) extends Containers filled material color Boxes length method 6 Cereal Boxes Cylinder extends length width height radius height type of cereal Software Boxes type of software extends Objects made from this class have all the attributes of the classes above them

11- 4 The Details, Defining a new Method, moveMile, inside a new class class MileWalker extends BasicRobot { void moveMile { move; move; move; move; move; move; move; move; } } New reserved words, class, extends, void

11- 5 Visually, What Have We Got? move turnLeft pickBeeper putBeeper turnOff BasicRobot x-location y-location direction num-beepers move turnLeft pickBeeper putBeeper turnOff moveMile MileWalker x-location y-location direction num-beepers extends

11- 6 So it is with Java Class C is a subclass of a class B: class C extends B { … } Objects of C contain all instance variables of B as well as those of C, respond to all the instance methods of B as well as of C, and C can redefine methods and override instance methods defined in B

11- 7 Example: Inheritance from class Time class Time { private int _hour, _minute; public Time (int h, int m) { _hour = h; _minute = m; } public void advanceMinutes (int m) { int totalMinutes = ((60*_hour) + _minute + m)% (24*60); if (totalMinutes < 0) totalMinutes = totalMinutes + (24*60); _hour = totalMinutes / 60; _minute = totalMinutes % 60; } public void printTime ( ) { … } // next page… }

public void printTime ( ) { if ((_hour == 0) && (_minute == 0)) System.out.print(“midnight”); else if ((_hour == 12) && (_minute == 0)) System.out.print(“noon”); else { if (_hour == 0) System.out.print(12); else if (_hour > 12) System.out.print(_hour - 12); elseSystem.out.print(_hour); if (_minute < 10) System.out.print(“:0”+ _minute); elseSystem.out.print(“:” + _minute); if (_hour < 12)System.out.print(“AM”); elseSystem.out.print(“PM”); } } } end of class Time

11- 9 Now We Want Customization So now we want to have a new class, to be used occasionally, called PreciseTime The class PreciseTime is mostly the same as Time, and we don't have to duplicate everything in Time, we'll just inherit from it However, PreciseTime will have a new instance variable, second, a new instance method, void advanceSeconds(int), and a new constructor

class PreciseTime extends Time { private int _second; public PreciseTime(int h, int m, int s) { super(h, m); _second = s; } public void advanceSeconds (int s) { int advMinutes = s / 60; _second += s % 60; if (_second < 0) { advMinutes--; _second += 60; } else if (_second >= 60) { advMinutes++; _second -= 60; } advanceMinutes(advMinutes); } }

PreciseTime Objects of the class PreciseTime have instance variables _hour, _minute, and _second They respond to messages advanceMinutes, printTime, and advanceSeconds A PreciseTime object is also a Time object advanceSeconds causes a PreciseTime object to send itself an advanceMinutes message

Example The program: public class Time1Mutate { public static void main (String[ ] args) { PreciseTime lunchtime = new PreciseTime(6, 10, 0); lunchtime.advanceSeconds(60); lunchtime.printTime( ); System.out.println( ); lunchtime.advanceSeconds(-61); lunchtime.printTime( ); System.out.println( ); } } Prints 6:11AM 6:09AM

Inheritance Hierarchy Obviously, a class can have any number of subclasses, those subclasses can have subclasses, etc., creating an inheritance hierarchy Notice that printTime( ) remains unchanged so far, even when we call it from a PreciseTime object

Everything's an Object… There's one special class, called Object, in the package java.lang All classes are considered descendants of Object. For example, Time actually extends Object: class Time { protected int _hour, _minute; … } We could write "class Time extends Object", but we don't have to

The Time Has Come, The Time is Now We have seen numerous examples of Class methods Math.pow(x, y) was a method associated with the class Math, that computes x y Similarly with Math.abs( ), Math.sqrt( ), etc. And let’s not forget the main method in our client programs; it is a method in a class, but we never created an object from that class! public static void main (String[ ] args) {...

Class Variables A Class Variable is a variable associated with the class, not with an object of the class There is only one instance of the class variable, not one instance per object To create a class variable, add the keyword “static” to the variable’s declaration

Class Method A Class Method is a method associated with the class as a whole, not with an object You can’t invoke a class method f using o.f (where o is an object name), since there’s no object it’s connected to Instead, you write C.f (where C is the class name) Add “static” to the method definition Class methods have no access to instance variables (of objects) in the class

Class and Objects _hour _minute Time addMinutes( int m ) void printTime( ) Time bill Attributes: _hour = 7 _minute = 18 Methods: Time addMinutes(int m) void printTime ( ) scott Attributes: _hour = 14 _minute = 41 Methods: Time addMinutes(int m) void printTime ( ) class objects

Motivation A Class method and Class variables allow us to define things which exist, in a single “copy”, in the class, and which are accessible to the objects that were derived from the class

Class and Objects with Class variables and Class Methods _hourstatic useMT _minute static void changeMT( ) Time addMinutes( int m ) void printTime( ) Time bill Attributes: _hour = 7 _minute = 18 Methods: Time addMinutes(int m) void printTime ( ) scott Attributes: _hour = 14 _minute = 41 Methods: Time addMinutes(int m) void printTime ( ) class objects

Example Let’s say the Time class has been expanded, so that now in addition to printTime( ) there is another method called printMilitaryTime( ) (prints 13:30 instead of 1:30PM) We want a boolean variable called useMilitaryTime to be used to decide which of the two methods should be used to print all of the Time objects Where should this boolean variable exist?

Possibility 1 Declare useMilitaryTime in the client program When printing object “now”, write: if (useMilitaryTime) now.printMilitaryTime( ); else now.printTime( );

Problem with Possibility 1 Printing of Time objects may occur in many different places, from many different methods, not necessarily in the main( ) class The useMilitaryTime variable would need to be passed to all of them as an additional argument Clumsy

Possibility 2 Make _useMilitaryTime an instance variable of Time, with an instance method that toggles it: public class Time { private boolean _useMilitaryTime = false; … public void toggleTimeFormat ( ) { _useMilitaryTime = !_useMilitaryTime; } public void printTime ( ) { if (_useMilitaryTime) … else … } }

Problem with Possibility 2 now.toggleTimeFormat( ) changes the printing format for object “now” now.printTime( ) prints appropriately But the boolean variable is repeated in every Time object that we’ve created Since we want to control all Time printing, we would need to send the toggleTimeFormat( ) message to all Time objects that have been created Clumsy

Where Should that Boolean Variable Sit? So putting the boolean variable in the client doesn’t work; too many different methods need access to it Putting it in the Time objects doesn’t work; we don’t really want multiple copies We need a variable that can be changed in a single place, and all objects have access to that shared variable

The Class Variable Solution Objects scott and bill have access to a single copy of a variable called useMT, that sits in the class Time; it doesn’t belong to any specific object, but to the class

public class Time { private static boolean _useMilitaryTime = false; … public static void toggleTimeFormat ( ) { _useMilitaryTime = !_useMilitaryTime; } public void printTime ( ) { if (_useMilitaryTime) … else … } } Both toggleTimeFormat( ) (the class method) and printTime( ) (the instance method) refer directly to useMilitaryTime (with no need to write Time.useMilitaryTime)

Use of the Class Method and Class Variable from Outside the Class If the client program writes: Time.toggleTimeFormat( ); then the single copy of useMilitaryTime in the class (referred to by all copies of printTime) is flipped The class variable could also be declared public, and referred to by Time.useMilitaryTime from outside the class

public class Time { private static boolean _useMilitaryTime = false; … public static void toggleTimeFormat ( ) { _useMilitaryTime = !_useMilitaryTime; } public void printTime ( ) { if (_useMilitaryTime) … else … } } Instance Methods Access Class Variables and Methods Class Methods Access Class Variables and Methods

Instances Access Class, Class Accesses Class, but Class Doesn’t Access Instances A class method cannot access instance variables or invoke instance methods Think about it: the class method (like Time.toggleTimeFormat( ) ) is called without reference to any particular object. Logically, what object would it access?

Container Classes, with no instance variables or methods There exist certain classes – container classes – whose whole purpose in life is to provide a convenient way of packaging a collection of methods They have no objects created from them; they have no constructors Math is an example of a class that simply provides a useful collection of methods: sin( ), sqrt( ), round( ), pow( ), abs( ), etc., and public static final doubles E and PI

Overloading Methods We created multiple constructors for a Class, all with the same name but different numbers or types of arguments: class Time { private int _hour, _minute; public Time (int h, int m) { _hour = h; _minute = m; } public Time ( ) { _hour = 0; _minute = 0; ) public Time (int m) { _hour = m / 60; _minute = m % 60; } public Time addMinutes (int m) { … } public void printTime ( ) { … } }

Example: Printing a formatted int or double We want to print a value, either an int or a double, in a field of given size w: w = 7; number is right justified We could define methods to handle formatted printing of int and double, and give them different names, but that’s not necessary with overloading

Overloading the printr Method The solution depends on two techniques First, to print a number, we can concatenate it with a string (which turns it into a string); this gives us a number right justified in a string of some length: String s = “ “ + i; For i = 3524, our string s would be 3524 number is right justified in the field of some length

Grabbing the Right Side of the String Second, we can select a substring consisting of the trailing (rightmost) w characters using the string methods length( ) and substring( ) If i has been combined with blanks into a string s, then s.substring(s.length( ) - w) gives us i right-justified in a field of width w

class Format { private static String _blanks=“ “; private static String setw(int w, int i) { String s = _blanks + i; return s.substring(s.length( ) -w); } private static String setw(int w, double d) { String s = _blanks + d; return s.substring(s.length( ) -w); } public static void printr(int w, int i) { System.out.print(setw(w, i)); } public static void printr(int w, double d) { System.out.print(setw(w, d)); } private overloaded class methods public overloaded class methods private class variable

What If the Overloading is Ambiguous? Format.printr(10, Math.PI) chooses the correct (second) version of printr( ) What about the following? static void f(int i, double x) { … } static void f(double x, int i) { … } … f(10, 20); Either version could be used You’ll get a compiler error