Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Similar documents
ECOM 2324 COMPUTER PROGRAMMING II

An Introduction To Writing Your Own Classes CSC 123 Fall 2018 Howard Rosenthal

Programming II (CS300)

Chapter 6 Introduction to Defining Classes

CLASSES AND OBJECTS IN JAVA

OO Programming Concepts. Classes. Objects. Chapter 8 User-Defined Classes and ADTs

Chapter 9 Objects and Classes. OO Programming Concepts. Classes. Objects. Motivations. Objectives. CS1: Java Programming Colorado State University

Object Oriented Programming in C#

Chapter 9 Objects and Classes. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved.

Lecture 7: Classes and Objects CS2301

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Programming II (CS300)

Programming II (CS300)

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Object-Oriented Programming Concepts

Chapter 4 Defining Classes I

Java Object Oriented Design. CSC207 Fall 2014

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Object-Oriented Programming Concepts

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

Chapter 8 Objects and Classes. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

CH. 2 OBJECT-ORIENTED PROGRAMMING

Chapter 9. Objects and Classes

C++ Classes, Constructor & Object Oriented Programming

JAVA MOCK TEST JAVA MOCK TEST II

OO Programming Concepts

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

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

Classes. Classes as Code Libraries. Classes as Data Structures. Classes/Objects/Interfaces (Savitch, Various Chapters)

COP 3330 Final Exam Review

Classes. Classes. Classes. Class Circle with methods. Class Circle with fields. Classes and Objects in Java. Introduce to classes and objects in Java.

Object Oriented Modeling

Anatomy of a Class Encapsulation Anatomy of a Method

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

Inf1-OOP. Data Types. Defining Data Types in Java. type value set operations. Overview. Circle Class. Creating Data Types 1.

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn how to describe objects and classes and how to define classes and create objects

Recommended Group Brainstorm (NO computers during this time)

CIS3023: Programming Fundamentals for CIS Majors II Summer 2010

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

Classes. Classes as Code Libraries. Classes as Data Structures

Programming in the Large II: Objects and Classes (Part 1)

Chapter 4. Defining Classes I

Simple Java Reference

CS 101 Exam 1 Spring 200 Id Name

Programming II (CS300)

Chapter 4: Writing Classes

COE318 Lecture Notes Week 3 (Week of Sept 17, 2012)

More About Objects and Methods. Objectives. Outline. Chapter 6

More About Objects and Methods

MIDTERM REVIEW. midterminformation.htm

Chapter 9 Objects and Classes. Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.

JAVA GUI PROGRAMMING REVISION TOUR III

AP COMPUTER SCIENCE A

Methods and Data (Savitch, Chapter 5)

Chapter 15: Object Oriented Programming

CS304 Object Oriented Programming Final Term


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

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

CS-202 Introduction to Object Oriented Programming

Chapter 5: Classes and Objects in Depth. Introduction to methods

Goal of lecture. Object-oriented Programming. Context of discussion. Message of lecture

Making New instances of Classes

ITI Introduction to Computing II

Principles of Object Oriented Programming. Lecture 4

Selected Questions from by Nageshwara Rao

2. Introducing Classes

2. [20] Suppose we start declaring a Rectangle class as follows:

Chapter 8 Objects and Classes Part 1

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

Inf1-OP. Creating Classes. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. February 26, School of Informatics

UFCE3T-15-M Object-oriented Design and Programming

Classes, interfaces, & documentation. Review of basic building blocks

Programming overview

Lecture Notes for CS 150 Fall 2009; Version 0.5

Comments are almost like C++

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

c) And last but not least, there are javadoc comments. See Weiss.

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

Chapter 8 Objects and Classes

Object Oriented Programming. Solved MCQs - Part 2

Example: Fibonacci Numbers

OBJECTS AND CLASSES CHAPTER. Final Draft 10/30/2011. Slides by Donald W. Smith TechNeTrain.com

Class Foo. instance variables. instance methods. Class FooTester. main {

Selected Java Topics

System.out.print(); Scanner.nextLine(); String.compareTo();

Programming Language Concepts: Lecture 2

Language Features. 1. The primitive types int, double, and boolean are part of the AP

ECE 122. Engineering Problem Solving with Java

Computer Science II (20073) Week 1: Review and Inheritance

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Transcription:

Based on Introduction to Java Programming, Y. Daniel Liang, Brief Version, 10/E 1 Creating Classes and Objects Classes give us a way of defining custom data types and associating data with operations on that appropriate for such data. An object represents an entity in the real world. For example: student, table, car, circle, university, book, bookstore. Objects have: state represented by data fields action/behavior defined by methods For example: circle has: state radius action/behavior getarea() getperimeter() setradius()... student has: state name id grades address... action/behavior computegpa() computemajorgpa() getid() changeaddress()... A class is a template for creating objects of the same type. For example, a Circle class can be used to create multiple Circle objects. A constructor is a special kind of method that is used to construct an object. A class can have multiple contstructors (i.e. different ways of creating objects). See SimpleCircle.java for an example of a class. 1

1 / / D e f i n e t h e c i r c l e c l a s s w i t h t w o c o n s t r u c t o r s 2 c l a s s S i m p l e C i r c l e { 3 p r i v a t e double r a d i u s ; 4 5 / C o n s t r u c t a c i r c l e w i t h r a d i u s 1 / 6 S i m p l e C i r c l e ( ) { 7 r a d i u s = 1 ; 8 } 9 10 / C o n s t r u c t a c i r c l e w i t h a s p e c i f i e d r a d i u s / 11 S i m p l e C i r c l e ( double newradius ) { 12 r a d i u s = newradius ; 13 } 14 15 / R e t u r n t h e a r e a o f t h i s c i r c l e / 16 double g e t A r e a ( ) { 17 return r a d i u s r a d i u s Math. PI ; 18 } 19 20 / R e t u r n t h e p e r i m e t e r o f t h i s c i r c l e / 21 double g e t P e r i m e t e r ( ) { 22 return 2 r a d i u s Math. PI ; 23 } 24 25 / S e t a n e w r a d i u s f o r t h i s c i r c l e / 26 void s e t R a d i u s ( double newradius ) { 27 r a d i u s = newradius ; 28 } 29 } 2 Constructors A constructor is a special method that is used to construct/create an object. Constructors have to obey several special rules: The name of the constructor is always the same as the name of the class, even if multiple constructors are present (uses method overloading). There is no return type, not even void. The constructor is called automatically when a new operator is used to create an object, ex. Circle c = new Circle(); The constructor that can be called with no arguments is called the default constructor or no-arg constructor. If a class has no constructors expicitly defined, Java provides a default constructor with empty body. It is provided only if NO constructors are defined in the class. Classes do not have to have a no-arg constructors 3 Reference Variables Objects The statement ClassName referencevariable; 2

declares a reference variable that can be used to store a memory address at which the actual object is stored. In order to create an object, you need to use the new operator referencevariable= new ClassName(...); This is similar to how an array-name stores the memory addresses of the location where the array is stored. The actual array storage needs to be allocated using the new operator. As with all the other declarations/creation statements, the above two lines can be combined into a single statement ClassName objectrefvariable = new ClassName(...); NOTE: observe the parenthesis in the last two statements. This is call to the constructor that may or may not take parameters. Example The following line of code creates a reference variable, unless it is followed by creation of an actual object, there is no room to store data. Person p; In fact, you should make a habit of always assigning the null value to a reference variable that does not actually reference any valid data: Person p = null; The new operator is used to create the actual object and to assign its memory address to a reference variable. p = new Person(); And since we do not really care about the hexadecimal value of the memory address, you ll see arrows used to show that a reference variable refers to or points to a memory location that contains the actual object. Anonymous objects. Occasionally, you may want to create an object in memory (usually temporary object) that is not pointed to by any object reference variable. Those objects are called anonymous objects, since they do not have a name. For example System.out.printf( The area of circle with radius %f is %f. \n, 5, new Circle(5).getArea() ); After this statement executes the object is still in the memory, but there is no way to access it. The memory that it occupies eventually gets reclaimed by Java garbage collection. 3

Common error Confusing object assignment with reference variable assignment. Circle c1 = new Circle(5); Circle c2 = new Circle(17); c1 = c2; The last statement results in c1 and c2 pointing to the same Circle object in memory (the one with radius 17). It does not copy one Circle object to another. This copies the reference of c1 into a new reference c2. c1 and c2 then refer to the same place in memory on the heap. 4 Accessing Object s Data and Methods The dot operator or object member access operator is used to access data fields and methods of an object: objectreferencename.datafield accesses specific data field in the object objectreferencename.method() invokes a specific method on the object The instance variables and instance methods are the variables and methods that can be accessed/invoked using a specific instance of the class (not using the class name). The object on which an instance method is invoked is called the calling object. We have been using the dot operator when we used methods in the String class. Example: The code String s = Hello NYU ; System.out.println( s.length() ); System.out.println( s.substring(6, 8) ); prints 9 NYU because s.length() returns the number of characters in the string s and s.substring (6, 8 ) returns a string that is a substring of s starting at index 6 up to index 8. 5 Default Values for Data Fields When a variable of any kind is created the memory associated with that variable contains some values. The data fields of a newly created object are filled, by default, with zero bits. Depending on the type of the data field, the interpretation of zeroed memory is slightly different. numerical types (for both integers and floating point numbers) - set to number zero char variables - set to \u0000, which is a null character, \0 or Boolean variables - set to false reference variables - set to null, which is an invalid memory address (from the point of view of the running program). NullPointerException occurs if you try to use a reference variable without assigning an object to it first. You will see a lot of these. 4

6 Using Classes from Java Library You have already seen some classes that come with Java. We will be using more and more of these. Math http://docs.oracle.com/javase/8/docs/api/java/lang/math.html Character http://docs.oracle.com/javase/8/docs/api/java/lang/character.html String http://docs.oracle.com/javase/8/docs/api/java/lang/string.html Arrays http://docs.oracle.com/javase/8/docs/api/java/util/arrays.html 7 static Variables and Methods, and Constants A static variable (class variables) is shared by all objects of the class. Such variables represent the whole class of objects, rather than one instance of the class (object). A static method (class method) is called on a class, rather than a specific object. Static methods do not have access to instance variables. static keyword in the declaration of a variable or method indicates that it is be a static variable/method. See CircleWithStaticMembers.java All methods in the Math class are static. In fact, you cannot create an instance of that class. Constants are shared among all instances of the class. They should be declared with final and static modifiers. 8 Visibility Modifiers: Four P s Data fields and methods There are four modifiers that can be used with data fields / methods in a class definitions (only one of these can be specified at a time, but the modifiers can be different for different data fields / methods in the same class): public package any other class in the world can access the data fields / methods (default, when no other modifier is specified) any other class in the same package can access the data fields / methods protected only members of the same class and subclasses (to be discussed in chapter 11) can access the data fields / methods private only the members of the same class can access the data fields / methods Constructors should be public in general. Exception: to prevent users of the class from creating an instance, for example, Math class has a private constructor. Classes The class itself can have an access modifier. Either public or nothing is used with a class. If no modifier is specified, only classes from within the same package can access the class. Each public class needs to be specified in its own file. 5

9 Encapsulation One of the main principles of OOP is to localize logic and data inside classes in order to create abstractions that can be used elsewhere in your program, without the programmer using them necessarily understanding the implementation of that abstraction. Do you understand how Scanner is implemented? No, right? Yet we use it in our programs. By localizing logic and data into our classes and making them available to be used by other classes, we achieve code reuse. Code reuse has many benefits, not the least of which is that it means we have to write less code by benefiting from the work of others. (Imagine if you had to write the String class in every program that wanted to use strings?) So how do we write code in this same manner? By localizing, or encapsulating, our logic and data in our classes and hiding that data and logic as much as possible from other classes. As a result, all data fields should be private to the class. If your data needs to be shared, then the class should provide public and getters / accessors / get methods setters / mutators / set methods to allow for controlled access to the data fields. Similarly, methods that are used only for the interal logic of a class should be marked private. Limit visibility of data and methods as much as possible. 10 Passing Objects to Methods See ObjectsAsArguments.java 11 Arrays of Objects See SortingCircles.java 6