UCLA PIC 20A Java Programming

Similar documents
Java OOP (SE Tutorials: Learning the Java Language Trail : Object-Oriented Programming Concepts Lesson )

Subclasses, Superclasses, and Inheritance

Java Object Oriented Design. CSC207 Fall 2014

UCLA PIC 20A Java Programming

Software Architecture (Lesson 2) Object-Oriented Paradigm (1)

PESIT Bangalore South Campus

CSIS 10A Practice Final Exam Solutions

Object-Oriented Programming Paradigm

Introduction and Review of Java: Part 2

Java Mouse Actions. C&G criteria: 5.2.1, 5.4.1, 5.4.2,

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

User interfaces and Swing

CS 120 Fall 2008 Practice Final Exam v1.0m. Name: Model Solution. True/False Section, 20 points: 10 true/false, 2 points each

Inheritance 2. Inheritance 2. Wolfgang Schreiner Research Institute for Symbolic Computation (RISC) Johannes Kepler University, Linz, Austria

8. Polymorphism and Inheritance

CSCI 053. Week 5 Java is like Alice not based on Joel Adams you may want to take notes. Rhys Price Jones. Introduction to Software Development

Allenhouse Institute of Technology (UPTU Code : 505) OOT Notes By Hammad Lari for B.Tech CSE V th Sem

Computer Science 210: Data Structures. Intro to Java Graphics

Lab 10: Inheritance (I)

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Chapter 6 Introduction to Defining Classes

Cheng, CSE870. More Frameworks. Overview. Recap on OOP. Acknowledgements:

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

CS313D: ADVANCED PROGRAMMING LANGUAGE

H212 Introduction to Software Systems Honors

CSSE 220 Day 15. Inheritance. Check out DiscountSubclasses from SVN

Inheritance. One class inherits from another if it describes a specialized subset of objects Terminology:

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Chapter 1 GUI Applications

Chapter 3: Inheritance and Polymorphism

CS313D: ADVANCED PROGRAMMING LANGUAGE

The class definition is not a program by itself. It can be used by other programs in order to create objects and use them.

OO Programming in C# Computing Resources. COMP104-11S Teaching Staff. COMP104-11S Textbooks

The Basics. Concepts of Class and Object

CSIS 10A PRACTICE FINAL EXAM Name Closed Book Closed Computer 3 Sheets of Notes Allowed

Inheritance (Part 5) Odds and ends

Exercise: Singleton 1

Chapter No. 2 Class modeling CO:-Sketch Class,object models using fundamental relationships Contents 2.1 Object and Class Concepts (12M) Objects,

Making New instances of Classes

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

CSCE3193: Programming Paradigms

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

Chapter 10 Classes Continued. Fundamentals of Java

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Java and OOP. Part 3 Extending classes. OOP in Java : W. Milner 2005 : Slide 1

Programming Languages and Techniques (CIS120)

CSE 21 Intro to Computing II. Inheritance

Computer Science 210: Data Structures

Inheritance and Polymorphism

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

J.73 J.74 THE I/O PACKAGE. Java I/O is defined in terms of streams. Streams are ordered sequences of data that have a source and a destination.

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

Inheritance and Interfaces

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created.

Using the API: Introductory Graphics Java Programming 1 Lesson 8

Java Programming Lecture 6

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 9: Writing Java Applets. Introduction

Road Map. Introduction to Java Applets Review applets that ship with JDK Make our own simple applets

Inheritance (Outsource: )

Programming overview

by Pearson Education, Inc. All Rights Reserved. 2

11/19/2014. Inheritance. Chapter 7: Inheritance. Inheritance. Inheritance. Java Software Solutions for AP* Computer Science A 2nd Edition

CS 170 Java Programming 1. Week 15: Interfaces and Exceptions

1 Definitions & Short Answer (5 Points Each)

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

Introduction to. Android Saturday. Yanqiao ZHU Google Camp School of Software Engineering, Tongji University. In courtesy of The Java Tutorials

CSSE 220. Event Based Programming. Check out EventBasedProgramming from SVN

OBJECT ORİENTATİON ENCAPSULATİON

Inheritance (Part 2) Notes Chapter 6

Week 9. Abstract Classes

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Learning the Java Language. 2.1 Object-Oriented Programming

GUI Event Handlers (Part I)

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

CompSci 230 Software Construction

About This Lecture. Data Abstraction - Interfaces and Implementations. Outline. Object Concepts. Object Class, Protocol and State.

2IS45 Programming

What are the characteristics of Object Oriented programming language?

An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

MODULE 8p - Applets - Trials B

Windows and Events. created originally by Brian Bailey

Object Oriented Software Design

JAVA: A Primer. By: Amrita Rajagopal

Java Programming Tutorial 1

CT 229 Arrays in Java

CS100J, Fall 2003 Preparing for Prelim 1: Monday, 29 Sept., 7:30 9:00PM

L4,5: Java Overview II

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018

INHERITANCE. Spring 2019

CS111: PROGRAMMING LANGUAGE II

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School

Transcription:

UCLA PIC 20A Java Programming Instructor: Ivo Dinov, Asst. Prof. In Statistics, Neurology and Program in Computing Teaching Assistant: Yon Seo Kim, PIC University of California, Los Angeles, Summer 2002 http://www.stat.ucla.edu/~dinov/ Chapter 2 Object Oriented Programming What Is an Object? What Is a Message? What Is a Class? Objects versus Classes What Is Inheritance? What Is an Interface? Coding objects, classes, inheritance, interfaces Slide 1 Slide 2 Objects Objects An object is a software bundle of variables and related methods. Real-world objects: your dog, desk, your TV set, your bicycle. Objects two characteristics: state and behavior. Ex., dogs have state (name, color, breed, hungry) and behavior (barking, fetching, and wagging tail). Ex., bicycles have state (current gear, current pedal cadence, two wheels, number of gears) and behavior (braking, accelerating, slowing down, changing gears). (Software) Objects are modeled after real-world objects in that they too have state and behavior. A software object maintains its state in one or more variables. A variable is an item of data named by an identifier. A software object implements its behavior with methods. A method is a function (subroutine) associated with an object. Definition: An object is a software bundle of variables and related methods. Slide 3 Slide 4 Objects guiding principles Messages Modularity: The source code for one object can be written and maintained independently of the source code for other objects. Also, an object can be easily passed around in the system. You can give your bicycle to someone else, and it will still work. Information hiding: An object has a public interface that other objects can use to communicate with it. An object can maintain private information and methods that can be changed without affecting the other objects that depend on it. You don t need to understand the gear mechanism on your bike to use it. A single object alone is generally not very useful. Instead, an object usually appears as a component of a larger program or application that contains many other objects. Your bicycle hanging from a hook in the garage is just a bunch of titanium alloy and rubber; by itself, the bicycle is incapable of any activity. The bicycle is useful only when another object (you) interacts with it (pedal). Software objects interact and communicate with each other by sending messages to each other. When object A wants object B to perform one of B s methods, object A sends a message to object B. Slide 5 Slide 6 1

Messages Messages Sometimes, the receiving object needs more information so that it knows exactly what to do; E.x., when you want to change gears on your bicycle, you have to indicate which gear you want. This information is passed along with the message as parameters. Note the Components that comprise a message: syntax T The object to which the message is addressed (Bicycle) T The name of the method to perform (changegear) T Any parameters needed by the method (lowergear) Messages provide two important benefits. T An object s behavior is expressed through its methods, so (aside from direct variable access) message passing supports all possible interactions between objects. T Objects don t need to be in the same process or even on the same machine to send and receive messages back and forth to each other. Ex, //since this view will also be changed, it will fire a property change to all the listeners firepropertychange("colormap", null, _colormodel); C:\Ivo.dir\LONI_Viz\LONI_Viz_MAP_demo\src.dir\edu\ucla\loni\LONI_Viz\ VolumeSliceView.java Slide 7 Slide 8 Classes Classes In the real world, you often have many objects of the same kind. For example, your bicycle is just one of many bicycles in the world. Using object-oriented terminology, we say that your bicycle object is an instance of the class of objects known as bicycles. Bicycles have some state (current gear, current size, two wheels) and behavior (change gears, brake) in common. However, each bicycle s state is independent of and can be different from that of other bicycles. When building bicycles, manufacturers take advantage of the fact that bicycles share characteristics, building many bicycles from the same blueprint. It would be very inefficient to produce a new blueprint for every individual bicycle manufactured. In object-oriented software, it s also possible to have many objects of the same kind that share characteristics: rectangles, employee records, video clips, and so on. Like the bicycle manufacturers, you can take advantage of the fact that objects of the same kind are similar and you can create a blueprint for those objects. A software blueprint for objects is called a class. Slide 9 Slide 10 Class vs. Instance Variables Objects vs. Classes Class variables: contain information that is shared by all instances of the class. For example, suppose that all bicycles had the same number of wheels (2 or 3). In this case, defining an instance variable to hold the number of wheels is inefficient; each instance would have its own copy of the variable, but the value would be the same for every instance. In such situations, you can define a class variable that contains the number of gears. All instances share this variable. If one object changes the variable, it changes for all other objects of that type. A class can also declare class methods. You can invoke a class method directly from the class, whereas you must invoke instance methods on a particular instance. ( E.g., System.out.println( Class Method ); ) Objects and Classes probably look very similar A blue-print of a bicycle is not a bicycle. The term object is sometimes used to refer to both classes and instances. Slide 11 Slide 12 2

Inheritance Inheritance Generally speaking, objects are defined in terms of classes. You know a lot about an object by knowing its class. Even if you don t know what a pennyfarthing is, if I told you it was a bicycle, you would know that it had two wheels, handle bars, and pedals. Object-oriented systems take this a step further and allow classes to be defined in terms of other classes. Mountain bikes, racing bikes, and tandems are all sub-classes of the bicycle (super-)class. Each subclass inherits state (in the form of variable declarations) from the tandems share some states: cadence, speed, and size, etc. Also, each subclass inherits methods from the superclass. Mountain bikes, racing bikes, and, each subclass inherits methods from the superclass. All bikes share some behaviors: braking and changing pedaling speed, for example. Bikes Mountain Racing Tandems Slide 13 Slide 14 Inheritance how are sub- & super-classes different? Subclasses are not limited to the state and behaviors provided to them by their superclass. Subclasses can add variables and methods to the ones they inherit from the superclass. Tandem bicycles have two seats and two sets of handle bars; some mountain bikes have an extra set of gears with a lower gear ratio. Subclasses can also override inherited methods and provide specialized implementations for those methods. For example, if you had a mountain bike with an extra set of gears, you would override the change gears method so that the rider could use those new gears. Inheritance how are sub- & super-classes different? You are not limited to just one layer of inheritance. Inheritance forms a tree, or class hierarchy, In general, the farther DOWN in the hierarchy a class appears, the more specialized its behavior. And the higher UP in the hierarchy a class is the more general it is! The Object class is at the top of class hierarchy, and each class is its descendant (directly or indirectly). For example, all classes inherit Object s tostring() method, which returns a string representation of the object. Slide 15 Slide 16 Interfaces Interfaces An interface is a device or a system that unrelated entities use to interact. According to this definition, a remote control is an interface between you and a television set, the English language is an interface between two people, and the protocol of behavior enforced in the military is the interface between people of different ranks. In Java, an interface is a device that unrelated objects use to interact with each other. An interface is probably most analogous to a protocol (an agreement on behavior). Definition: An interface is a device that unrelated objects use to interact with each other. An object can implement multiple interfaces. The bicycle class and its class hierarchy define what a bicycle can and cannot do in terms of its bicycleness. But bicycles interact with the world on other terms. For example, a bicycle in a store could be managed by an inventory program. An inventory program doesn t care what class of items it manages, as long as each item provides certain information, such as price and tracking number. Instead of forcing class relationships on otherwise unrelated items, the inventory program sets up a protocol of communication. The inventory interface would define, but not implement, methods that set and get the retail price, assign a tracking number, and so on. Slide 17 Slide 18 3

Interfaces Interfaces are useful for the following reasons: TCapturing similarities among unrelated classes without artificially forcing a class relationship TDeclaring methods that one or more classes are expected to implement TRevealing an object s programming interface without revealing its class Ex., ClickMe.java class (C:\Ivo.dir\UCLA_Classes\Summer2002\PIC20A\Examples\JavaTutorialExamples \java\concepts\example-1dot1\clickme.java) Local Objects: ClickMe, Spot, the three colors used in the applet (black, white, and red); an event object represents the user action of clicking the mouse, and so on. Classes: ClickMe & Spot Slide 19 Slide 20 public class Spot { //instance variables public int size; public int x,y; //constructor public Spot(int intsize) { size =intsize; x =-1; y =-1; The applet creates a new spot object when the applet is initialized. Here s the relevant code from the applet class: private Spot spot =null; private static final int RADIUS =7;... spot = new Spot(RADIUS); The first line shown declares a variable named spot whose data type is Spot, the class from which the object is created, and initializes the variable to null. The second line declares an int variable named RADIUS = 7. Finally, the last line shown creates the object; new allocates memory space for the object. Slide 21 Slide 22 Messages: g.setcolor(color.white); g.fillrect(0,0,getsize().width -1,getSize().height -1); Both are messages from the applet to an object named g a Graphics object that knows how to draw simple on-screen shapes and text. This object is provided to the applet when the browser instructs the applet to draw itself. The first line sets the color to white; The second fills a rectangle the size of the applet, thus painting the extent of the applet s area white. Slide 23 Inheritance: To run in a browser, an object must be an applet. The ClickMe applet object is an instance of the ClickMe class, which is declared like this: public class ClickMe extends Applet implements MouseListener {... The extends Applet clause makes ClickMe a subclass of Applet. ClickMe inherits a lot of capability from its superclass, including the ability to be initialized, started, and stopped by the browser; to draw within an area on a browser page; and to register to receive mouse events. Slide 24 4

Inheritance: Along with the benefits of being Applet s subclass, the ClickMe class has certain obligations: Its painting code must be in a method called paint, its initialization code must be in a method called init, etc. public void init(){... // ClickMe s initialization code here public void paint(graphics g){... // ClickMe s painting code here The ClickMe applet responds to mouse clicks by displaying a red spot at the click location. If an object wants to be notified of mouse clicks, the event system requires that the object implement the MouseListener interface. The object must also register as a mouse listener. The MouseListener interface declares five methods, each of which is called for a different kind of mouse event: when the mouse is clicked, moves outside of the applet, and so on. Even though the applet is interested only in mouse clicks, it must implement all five methods. The methods for the events that the applet isn t interested in are empty. Slide 25 Slide 26 import java.applet.applet; import java.awt.*; import java.awt.event.*; public class ClickMe extends Applet implements MouseListener { private Spot spot =null; private static final int RADIUS =7; public void init(){ addmouselistener(this); Slide 27 public void mousepressed(mouseevent event){ if (spot ==null){ spot =new Spot(RADIUS); spot.x =event.getx(); spot.y =event.gety(); repaint(); public void mouseclicked(mouseevent event){ public void mousereleased(mouseevent event){ public void mouseentered(mouseevent event){ public void mouseexited(mouseevent event){ Slide 28 API Docs EXTREMELY IMPORTANT: The ClickMe applet inherits a lot of capability from its superclass. To learn more about how ClickMe works, you need to learn about its superclass, Applet. How do you find that information? You can find detailed descriptions of every class in the API documentation, which constitutes the specification for the classes that make up the Java platform. The API documentation for the Java 2 Platform is online at java.sun.com. The documentation is also included on the CD that comes with our book. When appropriate, this book has footnotes providing the URLs to the API documents for particular classes. It s helpful to have the API documentation for all releases you use book marked in your browser. http://java.sun.com/j2se/1.3/docs/api/index.html Slide 29 5