Object-Oriented Programming Lecture 2: Classes and Objects



Similar documents
Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Introduction to Object-Oriented Programming

Chapter 1 Fundamentals of Java Programming

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

LAB4 Making Classes and Objects

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Part I. Multiple Choice Questions (2 points each):

Pemrograman Dasar. Basic Elements Of Java

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below:

3. Java Nuggets in a Nutshell

Java Classes. GEEN163 Introduction to Computer Programming

Java Interview Questions and Answers

Basic Object-Oriented Programming in Java

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

AP Computer Science Java Subset

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

More on Objects and Classes

Java CPD (I) Frans Coenen Department of Computer Science

JavaScript. JavaScript: fundamentals, concepts, object model. Document Object Model. The Web Page. The window object (1/2) The document object

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Java Programming Language

Moving from CS 61A Scheme to CS 61B Java

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

C++ INTERVIEW QUESTIONS

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

Object-Oriented Programming in Java

Java Application Developer Certificate Program Competencies

Object Oriented Software Design II

Glossary of Object Oriented Terms

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Install Java Development Kit (JDK) 1.8

Course Title: Software Development

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Introduction to Java Applets (Deitel chapter 3)

What is Java? Applications and Applets: Result of Sun s efforts to remedy bad software engineering practices

Description of Class Mutation Mutation Operators for Java

Java Crash Course Part I

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

OpenCL Static C++ Kernel Language Extension

Part 1 Foundations of object orientation

Programming Languages Featherweight Java David Walker

Chapter 13 - Inheritance

Principles of Software Construction: Objects, Design, and Concurrency. Course Introduction. toad. toad Fall School of Computer Science

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

Introduction: Abstract Data Types and Java Review

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

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

Lecture 5: Java Fundamentals III

Copyright. Restricted Rights Legend. Trademarks or Service Marks. Copyright 2003 BEA Systems, Inc. All Rights Reserved.

11 November

The C Programming Language course syllabus associate level

Fundamentals of Java Programming

Getting Started with the Internet Communications Engine

Example of a Java program

History OOP languages Year Language 1967 Simula Smalltalk

Chapter 13 Storage classes

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Object Oriented Software Design

UNIVERSITY OF CALIFORNIA BERKELEY Engineering 7 Department of Civil and Environmental Engineering. Object Oriented Programming and Classes in MATLAB 1

ATM Case Study OBJECTIVES Pearson Education, Inc. All rights reserved Pearson Education, Inc. All rights reserved.

Java is an Object-Oriented Language. As a language that has the Object Oriented feature, Java supports the following fundamental concepts:

CS193j, Stanford Handout #10 OOP 3

Abstract Class & Java Interface

Chapter 2: Elements of Java

Conversion Constructors

On the (un)suitability of Java to be the first programming language

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Constructor, Destructor, Accessibility and Virtual Functions

LAB 1. Familiarization of Rational Rose Environment And UML for small Java Application Development

Java Programming Fundamentals

Object Oriented Software Design

3 Pillars of Object-oriented Programming. Industrial Programming Systems Programming & Scripting. Extending the Example.

Let s start with a simple, object-oriented model of a point in two-dimensional space:

Java from a C perspective. Plan

JAVA - OBJECT & CLASSES

Java (12 Weeks) Introduction to Java Programming Language

Writing Self-testing Java Classes with SelfTest

Java How to Program, 5/e Test Item File 1 of 5

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Inheritance, overloading and overriding

Assignment # 2: Design Patterns and GUIs

VB.NET - CLASSES & OBJECTS

How to create/avoid memory leak in Java and.net? Venkat Subramaniam

Arrays in Java. Working with Arrays

Java SE 8 Programming

Unit Testing and JUnit

CS 111 Classes I 1. Software Organization View to this point:

No no-argument constructor. No default constructor found

csce4313 Programming Languages Scanner (pass/fail)

ProfBuilder: A Package for Rapidly Building Java Execution Profilers Brian F. Cooper, Han B. Lee, and Benjamin G. Zorn

Object-Oriented Programming in Java

Oracle v. Google: How Can Your Protect APIs?

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

Introducing Variance into the Java Programming Language DRAFT

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

Transcription:

Object-Oriented Programming Lecture 2: Classes and Objects Dr. Lê H!ng Ph"#ng -- Department of Mathematics, Mechanics and Informatics, VNUH July 2012 1

Content Class Object More on class Enum types Package and the class path Documentation comments for class Number and String 2

Class Recall that a class is a blueprint from which individual objects are created. Classes are defined in the following way: class MyClass { // field, constructor, and // method declarations The class body contains all the code that provides for the life cycle of the objects created from the class: Constructors for initializing new objects Declarations for the fields that provide the state of the class Methods to implement the behavior of the class and its objects 3

Class More complicated declaration of class: class MyClass extends MySuperClass implements YourInterface { // field, constructor, and // method declarations This means that MyClass is a subclass of MySuperClass and that it implements the YourInterface interface. You can add access modifiers like public, protected, private at the beginning, which determine what other classes can access MyClass (discuss later). 4

Declaring member variables There are several kinds of variables: Member variables in a class--these are called fields. Variables in a method or a block of code--these are called local variables. Variables in method declaration--these are called parameters. The Bicycle class uses the following lines of code to define its fields: int cadence; int speed; int gear; 5

Declaring member variables In the sprit of encapsulation, it is common to make fields private. This means that they can only be directly accessed from the Bicycle class. We are still able to access the field values from outside of the class through public methods defined by the class. class Bicycle { private int cadence; private int speed; private int gear; public Bicycle(int startcadence, int startspeed, int startgear) { gear = startgear; cadence = startcadence; speed = startspeed; void changecadence(int newvalue) { cadence = newvalue; void changegear(int newvalue) { gear = newvalue; void speedup(int increment) { speed = speed + increment; void applybrakes(int decrement) { speed = speed - decrement; 6

Naming rules and conventions All variables follow the same naming rules and conventions defined by the Java language. The same naming rules and conventions are used for methods and class names, except that The first letter of a class name should be capitalized. the first (or only) word in a method name should be a verb. 7

Defining methods An example of a typical method declaration: public double calculateanswer(double wingspan, int numberofengines, double length, double grosstons) { //do the calculation here The only required elements of a method declaration are the method s return type, name, a pair of parentheses, (), and a body between braces, {. Two of the elements of a method declaration comprise the method signature--the method s name and parameter types. calculateanswer(double, int, double, double) 8

Defining methods More generally, method declarations have 6 components, in order: 1. A modifier, such as public, protected, private; 2. The return type or void if the method does not return a value; 3. The method name which follow naming rules and conventions; 4. The parameter list in parentheses; this list can be empty; 5. An exception list (to be discussed later); 6. The method body, enclosed between braces. 9

Overloading methods The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists. public class DataArtist { //... public void draw(string s) { //... public void draw(int i) { //... public void draw(double f) { //... public void draw(int i, double f) { //... 10

Providing constructors A class contains constructors that are invoked to create objects from the class blueprint. Constructor declaration looks like method declaration, except that they use the same name of the class and have no return type. The class Bicycle has one constructor: public Bicycle(int startcadence, int startspeed, int startgear) { gear = startgear; cadence = startcadence; speed = startspeed; 11

Providing constructors To create a new Bicycle object called mybike, a constructor is called by the new operator: Bicycle mybike = new Bicycle(30, 0, 8); Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields. Bicycle class can define another constructor, for example: public Bicycle() { gear = 1; cadence = 10; speed = 0; Bicycle yourbike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourbike. 12

Providing constructors The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. If the superclass does not have a no-argument constructor, the compiler will complain, so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor. 13

Providing constructors You can use access modifiers in a constructor s declaration to control which other classes can call the constructor. Question: How to create a singleton object from a class? 14

Use a superclass constructor public class MountainBike extends Bicycle { // the MountainBike subclass has one field public int seatheight; // the MountainBike subclass has one constructor public MountainBike(int startheight, int startcadence, int startspeed, int startgear) { super(startcadence, startspeed, startgear); seatheight = startheight; // the MountainBike subclass has one method public void setheight(int newvalue) { seatheight = newvalue; 15

Passing information to a method or a constructor The following is a method that computes the monthly payments for a home loan, based on the amount of the loan, the interest rate, the number of periods, and the future value of the loan. public double computepayment(double loanamt, double rate, double futurevalue, int numperiods) { double interest = rate / 100.0; double partial1 = Math.pow((1 + interest), -numperiods); double denominator = (1 - partial1) / interest; double answer = (-loanamt / denominator) - ((futurevalue * partial1) / denominator); return answer; The name of a parameter must be unique in its scope. It cannot be the name of a local variable within the method. A parameter can have the same name as one of the class s fields, which is conventionally used only within constructors. 16

Passing primitive data type arguments Primitive arguments such as an int or a double are passed into methods by value. This means that any changes to the values of the parameters exist only within the scope of the method. public class PassPrimitiveByValue { public static void main(string[] args) { int x = 3; passmethod(x); System.out.println("x = " + x); public static void passmethod(int p) { p = 10; When the method returns, the parameters are gone and any changes to them are lost. 17

Passing reference data type arguments Reference data type parameters, such as objects, are also passed by value. This means that when the method returns, the passed-in reference still references the same object as before. However, the value of the object s fields can be changed in the method, if they have the proper access level. 18

Passing reference data type arguments public class Circle { private int x, y, radius; public void setx(int x) { this.x = x; public int getx() { return x; public int gety() { return y; public void sety(int y) { this.y = y; public void movecircle(circle circle, int deltax, int deltay) { // code to move origin of // circle to x+deltax, y+deltay circle.setx(circle.getx() + deltax); circle.sety(circle.gety() + deltay); // code to assign a new // reference to circle circle = new Circle(0, 0); Circle mycircle = new Circle(5, 5); movecircle(mycircle, 20, 50); What are the coordinates of mycircle after invoking this? 19

Passing reference data type arguments Inside the method, circle initially refers to mycircle. The method changes the x and y coordinates of the object that circle references (that is, mycircle). These changes will persist when the method returns. Then circle is assigned a reference to a new Circle object with x = y = 0. However, this assignment has no permanence because the reference was passed in by value and cannot change. When the method returns, mycircle still references the same Circle object as before the method was called. 20

Content Class Object More on class Enum types Package and the class path Documentation comments for class Number and String 21

Creating objects A class provides the blueprint for objects; you create an object from a class. Point originone = new Point(23, 94); Rectangle rectone = new Rectangle(originOne, 100, 200); Rectangle recttwo = new Rectangle(50, 100); Each of these statements creates an object and assigns it to a variable. Each statement has 3 parts: Declaration: associate a variable name with an object type; Instantiation: the new keyword is an operator that creates the object; Initialization: a call to a constructor which initializes the new object. 22

Declaring a variable to refer to an object To declare a variable: type name; With a primitive variable, this declaration reserves the proper amount of memory for the variable. If we declare a reference variable like this: Point originone; Its value will be undetermined until an object is actually created and assigned to it. You must create and assign an object to originone before you use it in your code; otherwise you will get a compilation error. The variable originone currently references to nothing: 23

Instantiating a class The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor. Point originone = new Point(23, 94); Here s the code for the Point class which has a single constructor: public class Point { public int x = 0; public int y = 0; Normally, fields are not public. public Point(int a, int b) { x = a; y = b; 24

Instantiating a class public class Rectangle { public int width = 0; public int height = 0; public Point origin; The class Rectangle has 4 constructors. Each constructor lets you provide initial values for the rectangle s size and origin, using both primitive and reference types. If a class has multiple constructors, they must have different signatures. The Java compiler differentiates the constructors based on the number and the type of the arguments. public Rectangle() { origin = new Point(0, 0); public Rectangle(Point p) { origin = p; public Rectangle(int w, int h) { origin = new Point(0, 0); width = w; height = h; public Rectangle(Point p, int w, int h) { origin = p; width = w; height = h; public void move(int x, int y) { origin.x = x; origin.y = y; public int getarea() { return width * height; 25

Instantiating a class Rectangle rectone = new Rectangle(originOne, 100, 200); public class Rectangle { public int width = 0; public int height = 0; public Point origin; //... public Rectangle(Point p, int w, int h) { origin = p; width = w; height = h; 26

Using objects Once an object is created, we can use it to do something: use the value of one of its fields; change one of its fields; call one of its methods to perform an action. Use a simple name for a field within its class, like this: System.out.println("Width and height are: " + width + ", " + height); 27

Using objects Code that is outside the object s class must use an object reference followed by the dot operator: objectreference.fieldname In the code outside Rectangle class and if we have an Rectangle object named rectone: System.out.println("Width of rectone: " + rectone.width); System.out.println("Height of rectone: " + rectone.height); Recall that the new operator returns a reference to an object. So we could use the value returned from new to access a new object s field: int height = new Rectangle().height; After executing this statement, the program has no longer reference to this created Rectangle, because the program never stored the reference anywhere (GC). 28

Calling an object s method To call an object s method: objectreference.methodname(argumentlist); The Rectangle class has two methods: move(int, int) to change the rectangle s origin, and getarea() to compute the rectangle s area. System.out.println("Area of rectone: " + rectone.getarea()); //... recttwo.move(40, 72); If some methods returns a value (such as getarea()), we can use the method invocation in expressions: int areaofrectangle = new Rectangle(100, 50).getArea(); 29

The garbage collector (GB) Some object-oriented languages require that you keep track of all the objects you create, and you explicitly destroy them when they are no longer needed. Managing memory explicitly is tedious and error-prone. The Java platform allows you to create as many objects as you want and you don t have to worry about destroying them. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection. 30

The garbage collector (GB) An object is eligible for garbage collection when there are no more references to that object: variables go out of scope; variables are explicitly set to null. The garbage collector periodically frees the memory used by the objects that are no longer referenced. The garbage collector does its job automatically when it determines that the time is right. 31