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;

Slides:



Advertisements
Similar presentations
Programming Paradigms Introduction. 6/15/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved. L1:
Advertisements

Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
. Smart Pointers. Memory Management u One of the major issues in writing C/C++ code is managing dynamically allocated memory u Biggest question is how.
IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
1 Chapter Three Using Methods. 2 Objectives Learn how to write methods with no arguments and no return value Learn about implementation hiding and how.
1 Objects, Classes, and Packages “Static” Classes Introduction to Classes Object Variables and Object References Instantiating Objects Using Methods in.
Rounding Out Classes The objectives of this chapter are: To discuss issues surrounding passing parameters to methods What is "this"? To introduce class.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
ECE122 L4: Creating Objects February 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 4 Creating and Using Objects.
CSE 2501 Review Declaring a variable allocates space for the type of datum it is to store int x; // allocates space for an int int *px; // allocates space.
Chapter Day 5. © 2007 Pearson Addison-Wesley. All rights reserved2-2 Agenda Day 5 Questions from last Class?? Problem set 1 Posted  Introduction on developing.
1 More on Inheritance Overview l Object: The father of all classes l Casting and Classes l Object Cloning l Importance of Cloning.
Pointer. Warning! Dangerous Curves C (and C++) have just about the most powerful, flexible and dangerous pointers in the world. –Most other languages.
U NIVERSITY OF M ASSACHUSETTS A MHERST Department of Computer Science Computer Systems Principles C/C++ Emery Berger and Mark Corner University of Massachusetts.
References, Aliases, Garbage Collection and Packages Packages and Importing Classes Reading for this Lecture: L&L, Familiarize yourself with.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
C++ fundamentals.
Arrays and Objects OO basics. Topics Basic array syntax/use OO Vocabulary review Simple OO example Instance and Static methods Static vs. instance vs.
Hello AP Computer Science!. What are some of the things that you have used computers for?
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
11 Getting Started with C# Chapter Objectives You will be able to: 1. Say in general terms how C# differs from C. 2. Create, compile, and run a.
Introduction to Object-oriented programming and software development Lecture 1.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Classes and Objects. Topics The Class Definition Declaring Instance Member Variables Writing Instance Member Methods Creating Objects Sending Messages.
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.
CSC Programming I Lecture 8 September 9, 2002.
CSSE501 Object-Oriented Development. Chapter 12: Implications of Substitution  In this chapter we will investigate some of the implications of the principle.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Effective C#, Chapter 1: C# Language Elements Last Updated: Fall 2011.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
C++ Memory Overview 4 major memory segments Key differences from Java
Object-Oriented Programming in C++
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Hello Computer Science!. Below is an example of a Hello World program in JAVA. While it is only three lines of code, there are many things that are happening.
Object-Oriented Programming Chapter Chapter
Object Oriented Software Development 4. C# data types, objects and references.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
Classes CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
Chapter 3 Implementing Classes
Chapter 1: Preliminaries Lecture # 2. Chapter 1: Preliminaries Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation.
© 2004 Pearson Addison-Wesley. All rights reserved September 5, 2007 Packages & Random and Math Classes ComS 207: Programming I (in Java) Iowa State University,
Basic Class Structure. Class vs. Object class - a template for building an object –defines the instance data that the object will hold –defines instance.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
Lecture 3 John Woodward.
Concepts of Object Oriented Programming
Creating Objects & String Class
Packages, Interfaces & Exception Handling
Object Based Programming
Subprograms and Programmer Defined Data Type
Object Oriented Programming Review
(Computer fundamental Lab)
Packages & Random and Math Classes
Java Programming Language
Programming Languages and Paradigms
Outline Creating Objects The String Class The Random and Math Classes
Classes and Objects Object Creation
CMSC 202 Constructors Version 9/10.
Presentation transcript:

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;  explain the term multiple inheritance;  explain the problem of aliasing in Java;  develop clone methods to avoid the problem of aliasing;  identify immutable objects;  explain the benefits of Java’s garbage collector.

Language size Java is relatively small and compact when compared to a traditional systems language like C (and its object- oriented successor C++). Java syntax is very similar to C++ syntax but it does not contain complex C++ features such as pointers and multiple inheritance.

Pointers vs references A pointer is a variable containing an address in memory. Java programmers can do something very similar to this – they can create references. The difference between a reference and a pointer is that the programmer does not have control over which address in memory is used – the system takes care of this. In a language like C++ the programmer can directly manipulate this pointer which could lead to critical areas of memory being corrupted.

Problems with multiple inheritance In Java a class can only ever inherit from, at most, one base class. Other languages (like C++ and Eiffel) allow multiple inheritance where a class inherits from more than one base class: Manager Player Player Manager a combination of single and multiple inheritance Employee The Java developers decided not to allow multiple inheritance for two reasons:  it is very rarely required;  it can lead to very complicated inheritance trees which in turn lead to programming errors. Although Java disallows multiple inheritance it does offer interfaces - a class can implement many interfaces.

Aliases in Java Aliasing occurs when the same memory location is accessed by variables with different names. Copying an object reference creates an alias: oblong1 attributes of object stored here oblong2 Oblong oblong1 = new Oblong(10, 20); Oblong oblong2 = oblong1 Computer Memory Java Instructions

The dangers of aliasing In practice a programmer would normally create an alias only with good reason: list[i] = list[i+1]; However, a potential problem with aliasing is that it could lead to errors arising inadvertently. Aliases could, unintentionally, break the principle of encapsulation by allowing write access to a private attribute.

An example of the dangers of aliases class Customer { // private attributes hold bank account details private BankAccount account1; private BankAccount account2; // more code here // two access methods public BankAccount getFirstAccount() { return account1; } public BankAccount getSecondAccount() { return account2; }

An example of the dangers of aliases The getFirstAccount and getSecondAccount methods send back a reference to a private attribute which allows users of this class to interrogate details about the two bank accounts, with statements such as: BankAccount tempAccount = someCustomer.getFirstAccount(); System.out.println(“balance of first account = ” + tempAccount.getBalance()); The problem is that this reference can also be used to manipulate the private attributes of the BankAccount object, with a statement like this: tempAccount.withdraw(100);

A solution to the problem of aliasing The problem of aliases arises when a copy of an object is required but instead a reference to an object is returned. By sending back a reference, the original object can be manipulated, whereas a copy would not cause any harm to the original object. In order to provide such a copy, a class should define a method that returns an exact copy of the object rather than a reference. Such a method exists in the Object class but has to be overridden in any user defined class. The method is called clone.

The clone method The clone method that needs to be redefined in each user-defined class has the following outline: public Object clone() { // code goes here } Here is a clone method for the BankAccount class: public Object clone() { BankAccount copyOfThisAccount = new BankAccount(accountNumber, accountName); copyOfThisAccount.balance = balance; return copyOfThisAccount; }

The clone method creates a copy of an object ourAccount attributes of object stored here tempAccount attributes of object stored here BankAccount ourAccount = new BankAccount (“ ”, “Charatan and Kans”); BankAccount tempAccount = (BankAccount) ourAccount.clone(); Computer Memory Java Instructions

Amending the Customer class class Customer { // as before here // next two methods send back clones, not aliases public BankAccount getFirstAccount() { return (BankAccount)account1.clone(); } public BankAccount getSecondAccount() { return (BankAccount)account2.clone(); }

Immutable objects Objects which have no methods to alter their state are known as immutable objects. Aliases of an immutable objects cause no harm as there are no methods that allow the object to be altered. Here Book objects are immutable so there is no problem with the getBook method of BookTable sending back an alias. BookTable books: Hashtbale BookTable() addBook(Book) removeBook(String) getBook(String): Book getBooks(): Enumeration Book isbn: String author: String title: String Book(String, String, String) getISBN():String getAuthor():String getTitle():String *

Garbage collection Computer memory could become exhausted when memory that is no longer needed is not released back to the system. Java has a built in garbage collection facility to release unused memory. This is a facility that regularly trawls through memory looking for locations used by the program, freeing any locations that are no longer in use.

class Tester { public static void main(String[] args) { char ans; Oblong object; // reference to object created here do { System.out.print("Enter length: "); double length = EasyIn.getDouble(); System.out.print("Enter height: "); double height = EasyIn.getDouble(); // new object created each time we go around the loop object = new Oblong(length, height); System.out.println("area = "+ object.calculateArea()); System.out.print("Do you want another go? "); ans = EasyIn.getChar(); } while (ans == 'y' || ans == 'Y'); } Without a garbage collector the following program could exhaust memory.