Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 8.

Slides:



Advertisements
Similar presentations
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 14.
Advertisements

CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Inheritance Inheritance Reserved word protected Reserved word super
Road Map Introduction to object oriented programming. Classes
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Inheritance. 2 Inheritance allows a software developer to derive a new class from an existing one The existing class is called the parent class or superclass.
CSCI 143 OOP – Inheritance 1. What is Inheritance? A form of software reuse Create a new class from an existing class – Absorb existing class data and.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
16/22/2015 2:54 PM6/22/2015 2:54 PM6/22/2015 2:54 PMObject-Oriented Development Concept originated with simulating objects and their interactions. Adapted.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Computer Science I Inheritance Professor Evan Korth New York University.
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.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
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.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
What is inheritance? It is the ability to create a new class from an existing class.
Mark Fontenot CSE Honors Principles of Computer Science I Note Set 14.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
1 Chapter 8 – Classes and Object: A Deeper Look Outline 1 Introduction 2 Implementing a Time Abstract Data Type with a Class 3 Class Scope 4 Controlling.
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
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.
Programming in Java CSCI-2220 Object Oriented Programming.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Inheritance and Access Control CS 162 (Summer 2009)
Computer Science 111 Fundamentals of Computer Programming I Working with our own classes.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables.
Object Oriented Programming
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
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:
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 12.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Inheritance ITI1121 Nour El Kadri.
Chapter 3: Using Methods, Classes, and Objects
Road Map Inheritance Class hierarchy Overriding methods Constructors
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Object Based Programming
Advanced Programming Behnam Hatami Fall 2017.
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Presentation transcript:

Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 8

Note Set 8 Overview Objects in depth Interface of a class Review of Access to members the this reference Overloaded Constructors Default and No Arg constructors

Time Class public class Time1 { private int hour; private int minute; private int second; public void setTime(int h, int m, int s) { hour = ((h >= 0 && h < 24) ? h : 0); minute = ((m >= 0 && m < 60) ? m : 0); second = ((s >= 0 && s < 60) ? m : 0); } public String toUniversalString() { return String.format(“%02d:%02d:%02d”, hour, minute, second); } public String toString () { return String.format(“%d:%02d:%02d %s”, ((hour == 0 || hour == 12) ? 12 : hour % 12 ), minute, second, (hour < 12 ? “AM” : “PM”) ); } Public Interface Time is a class. Objects of type Time provide a service. The services are indicated by the public interface

Time Class public class Time1 { private int hour; private int minute; private int second; public void setTime(int h, int m, int s) { hour = ((h >= 0 && h < 24) ? h : 0); minute = ((m >= 0 && m < 60) ? m : 0); second = ((s >= 0 && s < 60) ? m : 0); } public String toUniversalString() { return String.format(“%02d:%02d:%02d”, hour, minute, second); } public String toString () { return String.format(“%d:%02d:%02d %s”, ((hour == 0 || hour == 12) ? 12 : hour % 12 ), minute, second, (hour < 12 ? “AM” : “PM”) ); } methods that modify private instance variables should perform error checking – keeps object in consistent state more elegant error checking to come methods that modify private instance variables should perform error checking – keeps object in consistent state more elegant error checking to come

Time Class public class Time1 { private int hour; private int minute; private int second; public void setTime(int h, int m, int s) { hour = ((h >= 0 && h < 24) ? h : 0); minute = ((m >= 0 && m < 60) ? m : 0); second = ((s >= 0 && s < 60) ? m : 0); } public String toUniversalString() { return String.format(“%02d:%02d:%02d”, hour, minute, second); } public String toString () { return String.format(“%d:%02d:%02d %s”, ((hour == 0 || hour == 12) ? 12 : hour % 12 ), minute, second, (hour < 12 ? “AM” : “PM”) ); } Every object has a toString() method (implicitly or explicity) Called implicitly whenever a Time object needs to be converted to a string, such as in a printf. Every object has a toString() method (implicitly or explicity) Called implicitly whenever a Time object needs to be converted to a string, such as in a printf.

Time1Test public class Time1Test { public static void main (String [] args) { Time1 time = new Time1(); time.setTime(13, 27,6); System.out.print(“Initial Universal Time: “); System.out.println(time.toUniversalString()); System.out.print(“Initial Standard Time: “); System.out.println(time.toString()); System.out.println(); time.setTime(99, 99, 99); System.out.print(“Universal Time: “); System.out.println(time.toUniversalString()); System.out.print(“Standard Time: “); System.out.println(time.toString()); } Initial Universal Time: 13:27:06 Initial Standard Time: 1:27:06 PM Universal Time: 00:00:00 Standard Time: 12:00:00 AM Initial Universal Time: 13:27:06 Initial Standard Time: 1:27:06 PM Universal Time: 00:00:00 Standard Time: 12:00:00 AM

Time1Test public class Time1Test { public static void main (String [] args) { Time1 time = new Time1(); time.setTime(99, 99, 99); System.out.print(“Universal Time: “); System.out.println(time.toUniversalString()); System.out.print(“Standard Time: “); System.out.println(time.toString()); } Classes simplify the programming here. We don’t care how this happens, we just know it does. Details are abstracted away in the object’s implementation Clients usually care about what the class does but not how it does it Clients are not affected by a change in implementation. Interfaces change less frequently than implementation You might find a more efficient way of doing this or that later, but you don’t want to break code that depends on the fact that you can do this or that in some wha

Time1Test public class Time1Test { public static void main (String [] args) { Time1 time = new Time1(); time.hour = 7; time.minute = 15; time.second = 30; } Illegal – cannot access the private data members directly. Must go through the interface methods that are supplied by the class.

The this object reference Every object can access a reference to itself with keyword this. When a non-static method is called, the calling object is passed implicitly to the method Time t = new Time(); t.setTime( 12, 13, 14); System.out.println( t.toString() ); t is passed to the toString method implicitly. in toString, it can be refferenced through the this reference variable.

this public void setTime(int h, int m, int s) { hour = ((h >= 0 && h < 24) ? h : 0); minute = ((m >= 0 && m < 60) ? m : 0); second = ((s >= 0 && s < 60) ? m : 0); } How can these variables be accessed if they have no declaration? They were declared when the object that called this method was instantiated. They are referring to those variables that are part of the invoking object. public void setTime(int h, int m, int s) { this.hour = ((h >= 0 && h < 24) ? h : 0); this.minute = ((m >= 0 && m < 60) ? m : 0); this.second = ((s >= 0 && s < 60) ? m : 0); } Equivalent

Using this to avoid shadowing public class Test { private int a, b, c; public void foo(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } Accesses the instance data members instead of the parameters.

Overloaded constructors public class Test { private int a; public Test() { this(0); } public Test(int x) { a = x; } Call another constructor using the this reference. Calling another constructor with this must be the 1 st line in the body of the constructor Concentrate init logic in one method See Fig 8.5 – Time2.java

Special constructor public class Time2 { //Declarations public Time2 (Time2 time){ this(time.getHour(), time.getMinute(), time.getSecond()); } }

Accessing sets and gets in the class Reusability – concentrate logic to set value and get value in one area – the accessors and mutators. Consider if time was represented as an int holding number of seconds since midnight rather than 3 ints. if you have many time objects, this can be a space saver – from 12 bytes down to 4. If all conversion is done in set and get, then don’t have to worry about modifying the same logic twice (or getting it wrong twice).

Set and Get vs. public data Why not just make the instance variables public?

You might have noticed… Classes interact in your programs An instance method might receive an object as a parameter (even just at string) Once class might have an object of a different type as an instance variable public class MyClass { private Point x; A class might absorb the functionality of another class and add new attributes and functionality You make copious use of the Java API that contains a vast amount of pre-written, well-tested code

Software Reusability No need to “reinvent the wheel” Allows software developers to use Java API or other APIs that are well tested Rapid Application Development RAD Software reusability speeds the development of high-quality software

Composition – has-a When a class has references to objects of other classes as members. Great example of software re-use public class CardShoe { private Card [] cards; //other members } A CardShoe Object contains an array of Card objects CardShoe has access to all of the public members of the Card class. CardShoe does not have access to any of the private members of Card CardShoe HAS-A card

has-a & composition Car has-a motor motor has-a transmission Student has-a address address has-a street frame has-a panel Other examples?

Garbage Collection in Java When you allocate new objects, space is used in RAM as well as other system resources (network, files, etc). What releases these resources? JVM performs Garbage Collection to reclaim memory occupied by objects that are no longer in use Garbage collector does not necessarily release other system resources such as files, etc. System.gc(); //asks for GC to happen can use the finalize method in a class to clean-up allocated or reserved resources. Called by GC if GC attempts to reclaim an object – no guarantees though – GC might not actually run

Static class members Two types of members of a class Static variable ONLY one no matter how many objects of a type are allocated on a PER-CLASS basis Instance variables One for EVERY object that is instantiated on a PER-OBJECT basis public class Test { private int x; private int y; private static int count; //methods } //Before the two object are allocated Test obj1; Test obj2; Memory obj1 obj2 x x y y x x y y count Count exists in memory before any objects of type Test are allocated

When to Static??? When to Instance??? If every object of a particular type needs access to the same exact piece(s) of data, then make it static. If a division of employees makes produces more than 500K in profit for the company, then they get a 10% bonus based on salary public class Division { //An Employee obj Contains vital info including salary private Employee[] emps; public static double totalProfitForDiv; //other methods }

Static Methods Static Methods have access to static members (other static methods or static data) Cannot access instance variables – because they aren’t instance methods – doesn’t make sense Access using name of class and dot (.) public class Division { //An Employee obj Contains vital info including salary private Employee[] emps; public static double totalProfitForDiv; //other methods public static double getTotalProfit(){ //This method cannot access any element of emps return totalProfitForDiv; }

Inheritance One of the cornerstones of OOP A type of software re-use A new class is created by absorbing the members of an existing class and adding to or modifying those absorbed members Instead of the has-a relationship, Inheritance involves the is-a relationship. MultiplicationPanel is-a JPanel (has-a doesn’t make sense)

Terminology subclass vs superclass subclass inherits the members of the super class public class MultiplicationPanel extends JPanel In an is-a relationship, a subclass object may be treated as an object of its superclass. subclasssuperclass JPanel MultiplicationPanel

Class Object Object is the top level class in every inheritance hierarchy Every class extends Object implicitly if it doesn’t extend another class explicitly public class Person{ private String name; private String address; } Object Person public class Employee extends Person{ private float salary; } Object Person Employee

Some Inheritance Examples Student UndergradStudent Grad Student Circle Triangle Rectangle Shape BankAccount CheckingAccount SavingsAccount

Code public class Person { private String name; public Person (String s) { name = s; } public String getName() { return name; } public class Student extends Person{ private float gpa; public void setGpa(float g) { gpa = g; } public float getGpa() { return gpa; } extends indicates inheritance Student has everything from person plus whatever new “stuff” it adds

Code public class Person { private String name; public void setName(String s){ name = s; } public String getName() { return name; } public class Student extends Person{ private float gpa; public void setGpa(float g) { gpa = g; } public float getGpa() { return gpa; } In Main : Student s = new Student(); name gpa s s has the data from both Person and Student Any public member from Person or Student can be called on object s.

Protected access public – can be seen/accessed/called from outside the class private – can only be seen/accessed/called from inside the class protected – can be only be seen/accessed/called from inside the class AND from subclasses ?1 – Does a subclass have access to directly modify a private instance variable of the superclass? _____________ ?2 – Does a subclass have access to directly modify a protected instance variable of the superclass? ____________

Code – Private Name public class Person { private String name; public Person (String s) { name = s; } public String getName() { return name; } public class Student extends Person{ private float gpa; public void setGpa(float g) { gpa = g; } public float getGpa() { return gpa; } public void setData (String s, float g) { name = s; gpa = g; } method setData does not have access to private data member name from Person

Code – Protected Name public class Person { protected String name; public Person (String s) { name = s; } public String getName() { return name; } public class Student extends Person { private float gpa; public void setGpa(float g) { gpa = g; } public float getGpa() { return gpa; } public void setData (String s, float g) { name = s; gpa = g; } Now this is OK because name has protected visibility – can be directly access by subclasses Inherited members maintain their visibility in subclasses. So – a protected member of the superclass is a protected member of the subclass and a public member of the superclass is a public member of the subclass.