Chapter 7 Objects and Classes

Slides:



Advertisements
Similar presentations
Chapter 6 Objects and Classes F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and.
Advertisements

L3:CSC © Dr. Basheer M. Nasef Lecture #3 By Dr. Basheer M. Nasef.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 7 Objects and Classes.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 8 Objects and Classes.
Road Map Introduction to object oriented programming. Classes
1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 7 Objects and Classes.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Introduction to Java Programming, 4E Y. Daniel Liang.
Advanced Java and Android Day 1 Object-Oriented Programming in Java Advanced Java and Android -- Day 11.
Chapter 9 Objects and Classes
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
Syllabus (1) WeekChapters 1Introduction to the course, basic java language programming concepts: Primitive Data Types and Operations 1, 2 2Methods, Control.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Objects and Classes.
1 Objects and Classes. 2 OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 8 Objects and Classes.
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
1 Introducing Methods A method is a collection of statements that are grouped together to perform an operation.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 7 Objects and Classes.
1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.
1.  At the end of this slide, student able to:  Object-Oriented Programming  Research on OOP features.  Do a code walkthrough to examine the implementation.
Chapter 8 Objects and Classes Object Oriented programming Instructor: Dr. Essam H. Houssein.
Objects and Classes Mostafa Abdallah
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Objects and Classes.
Liang, Introduction to Java Programming, Sixth Edition1 Objects and Classes Gang Qian Department of Computer Science University of Central Oklahoma.
1 COS240 O-O Languages AUBG, COS dept Lecture 12 Title: Java Classes and Objects Reference: COS240 Syllabus.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 7 Objects and Classes.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Objects and Classes.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Objects and Classes.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 7 Objects and Classes.
1 Chapter 6 Programming with Objects and Classes F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive.
Introduction To Objects Oriented Programming Instructor: Mohammed Faisal.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 8 Objects and Classes.
Chapter 7 Objects and Classes. OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity.
CS 112 Programming 2 Lecture 02 Objects and Classes (1)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Fall 2013 Chapter 8 Objects.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 7 Objects and Classes.
Object-Oriented Programming in Java. 2 CS2336: Object-Oriented Programming in Java Buzzwords interfacejavadoc encapsulation coupling cohesion polymorphic.
1 COS240 O-O Languages AUBG, COS dept Lecture 12 Title: Java Classes and Objects Reference: COS240 Syllabus.
1 Chapter 9 Objects and Classes. 2 OO Programming in Java Other than primitive data types (byte, short, int, long, float, double, char, boolean), everything.
Lecture 9: Object and Classes Michael Hsu CSULA. 2 OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object.
Dr. Majed Abdouli © Objects and Classes 1 Dr. Majed Abdouli © 2015, adapted from Liang, Introduction to Java Programming, Eighth Edition, (c) 2011.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 8 Objects and Classes.
Chapter 7 Objects and Classes
Lecture 3: Introduction to Object and Classes
HIGHLEVEL REVIEW Chapter 9 Objects and Classes
Corresponds with Chapter 7
Chapter 8 Objects and Classes Part 1
Chapter 9 Objects and Classes
Chapter 9 Objects and Classes
Chapter 8 Objects and Classes
Objects and Classes Creating Objects and Object Reference Variables
Chapter 9 Objects and Classes
Chapter 6 Objects and Classes
Chapter 6 Objects and Classes
Chapter 8 Objects and Classes
Chapter 9 Objects and Classes
Chapter 9 Objects and Classes Part 01
Chapter 7 Objects and Classes
OO Programming Concepts
Chapter 6 Objects and Classes
Chapter 9 Objects and Classes
Chapter 8 Objects and Classes Part 2
Presentation transcript:

Chapter 7 Objects and Classes

OO Programming Concepts An Object corresponds to entity in the real world. Each object has a unique identity state – properties that can change in value behaviors – what can the object do?

OO Programming Concepts An object encapsulates (wraps together) attributes (data) behaviors (methods) Goal: Information Hiding

OOP Interface - what the object can do, proper usage vs. Implementation – how the object works

Objects An object has both a state and behavior. The state defines the object, and the behavior defines what the object does.

Classes Classes define objects of the same type. Class consists of Variables – data Methods – behavior

Constructors Methods that are used to instantiate a class Have the same name as the class Do not return a value Note: a method can have the same name as the class and have a return type - It’s not a constructor!

Classes

UML Class Diagram

Constructors Constructors are a special kind of methods that are invoked to construct objects. Circle() { } Circle(double newRadius) { radius = newRadius;

Constructors, cont. Constructors · have the same name as class ·       have no return type—not even void ·       invoked using new operator at object creation Constructors initialize objects. Constructors can be overloaded.

Creating Objects Using Constructors new ClassName(); Example: new Circle(); new Circle(5.0);

Default Constructor A class may be declared without constructors. A constructor with no parameters is referred to as a no-arg constructor. No-arg constructor with empty body is implicitly declared. This default constructor is provided automatically only if no constructors are explicitly declared.

Declaring Object Reference Variables To reference an object, assign the object to a reference variable. Syntax: ClassName objectRefVar; Example: Circle myCircle;

Declaring/Creating Objects in a Single Step ClassName objectRefVar = new ClassName(); Example: Circle myCircle = new Circle(); Assign object reference Create an object

Dot Operator Referencing the object’s data: objectRefVar.data e.g., myCircle.radius Invoking the object’s method: objectRefVar.methodName(arguments) e.g., myCircle.getArea()

A Simple Circle Class Objective: Demonstrate creating objects, accessing data, and using methods. TestCircle1 Run

Trace Code animation Declare myCircle Circle myCircle = new Circle(5.0); SCircle yourCircle = new Circle(); yourCircle.radius = 100; myCircle no value

Trace Code, cont. animation Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle no value Create a circle

Assign object reference to myCircle animation Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value Assign object reference to myCircle

Trace Code, cont. Declare yourCircle animation Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value yourCircle no value Declare yourCircle

Create a new Circle object animation Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value yourCircle no value Create a new Circle object

Assign object reference to yourCircle animation Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value yourCircle reference value Assign object reference to yourCircle

Change radius in yourCircle animation Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value yourCircle reference value Change radius in yourCircle

Caution We use Math.methodName(arguments) (e.g., Math.pow(3, 2.5)) to invoke a method in the Math class. Can you invoke getArea() using Circle.getArea()? NO! All the methods used before this chapter are static methods, which are defined using the static keyword. However, getArea() is non-static. It must be invoked from an object using objectRefVar.methodName(arguments) (e.g., myCircle.getArea()).

Reference Data Fields The data fields can be of primitive types OR reference types - Composition of objects For example, the following Student class contains a data field name of the String type. public class Student { String name; // name has default value null int age; // age has default value 0 boolean isScienceMajor; // isScienceMajor has default value false char gender; // c has default value '\u0000' }

The null Value If data field of reference type does not reference any object, it holds a special literal value, null.

Default Values Data fields of an object have default values. Variables defined in a method do not assume default values.

Default Value for a Data Field Default value of data field: null for reference type 0 for a numeric type false for a boolean type '\u0000' for char type. public class Test { public static void main(String[] args) { Student student = new Student(); System.out.println("name? " + student.name); System.out.println("age? " + student.age); System.out.println("isScienceMajor? " + student.isScienceMajor); System.out.println("gender? " + student.gender); }

Example Java assigns no default value to a local variable inside a method. public class Test { public static void main(String[] args) { int x; // x has no default value String y; // y has no default value System.out.println("x is " + x); System.out.println("y is " + y); } Compilation error: variables not initialized

Differences between Variables of Primitive Data Types and Object Types

Copying Variables of Primitive Data Types and Object Types

Garbage Collection An assignment statement such as c1=c2 results in 2 objects pointing to the same object. The object previously referenced by c1 is no longer referenced so it is garbage. Garbage is automatically collected by JVM.

Garbage Collection, cont TIP: If an object is no longer needed, explicitly assign null to a variable that references the object. The JVM automatically collects the space of an object not referenced by any variable.

The Date Class Java provides a system-independent encapsulation of date and time in the java.util.Date class. You can use the Date class to create an instance for the current date and time and use its toString method to return the date and time as a string.

The Date Class Example For example, the following code   java.util.Date date = new java.util.Date(); System.out.println(date.toString()); displays a string like Sun Mar 09 13:50:19 EST 2003.

The Random Class You have used Math.random() to obtain a random double value between 0.0 and 1.0 (excluding 1.0). A more useful random number generator is provided in the java.util.Random class.

The Random Class Example If two Random objects have the same seed, they will generate identical sequences of numbers. For example, the following code creates two Random objects with the same seed 3. Random random1 = new Random(3); System.out.print("From random1: "); for (int i = 0; i < 10; i++) System.out.print(random1.nextInt(1000) + " "); Random random2 = new Random(3); System.out.print("\nFrom random2: "); System.out.print(random2.nextInt(1000) + " "); From random1: 734 660 210 581 128 202 549 564 459 961 From random2: 734 660 210 581 128 202 549 564 459 961

Instance Variables, and Methods Instance variables belong to a specific instance. Instance methods are invoked by an instance of the class. The dot operator

Static Variables, Constants, and Methods Static variables are shared by all the instances of the class, class-wide information. Static methods are not tied to a specific object. Static constants are final variables shared by all the instances of the class.

Static Variables, Constants, and Methods, cont. To declare static variables, constants, and methods, use the static modifier. The members of the math class are defined as static. That’s why we never create an object of type Math, yet we can use its methods.

Static Variables, Constants, and Methods, cont.

Example of Using Instance and Class Variables and Method Objective: Demonstrate the roles of instance and class variables and their uses. This example adds a class variable numberOfObjects to track the number of Circle objects created. Circle2 TestCircle2 Run

Final instance variables A final variable is not modifiable. A constant can be initialized In its declaration By constructors Syntax error: not initializing constant variable at declaration or in every constructor.

Access to a Class Access level modifiers determine whether other classes can use a particular field OR or invoke a particular method.

Access Control Top Level Member Level Public Package-private (no explicit modifier) Member Level Private Protected – in any subclass or within package

Access Levels Modifier Class Package Subclass World Public Y Protected N No modifier Private

Visibility Modifiers and Accessor/Mutator Methods By default, the class, variable, or method can be accessed by any class in the same package. public The class, data, or method is visible to any class in any package. private The data or methods can be accessed only by the declaring class.

Top Level Access Modifiers Member Level Access Modifiers

NOTE An object cannot access its private members, as shown in (b). It is OK, however, if the object is declared in its own class, as shown in (a).

Summary Modifier Access Private within class within package Public unrestricted access

Why Data Fields Should Be private? To protect data. To make class easy to maintain.

Private Variables How can private data be used by other objects? Accessor (get) methods To read private data Mutator (set) methods To modify private data

Example of Data Field Encapsulation Circle3 TestCircle3 Run

Passing Objects to Methods Passing by value for primitive type value (the value is passed to the parameter) Passing by value for reference type value (the value is the reference to the object, essentially pass by reference) TestPassObject Run

Passing Objects to Methods, cont.

This An object can access a reference to itself: keyword this Method can declare a local variable with same name as a field. Local variable shadows field Use this.field_name to access field A constructor can invoke another constructor of the same class. this (parameter_list);

Reference the Hidden Data Fields

Calling Overloaded Constructor

Array of Objects Array of objects: array of reference variables. Circle[] circleArray = new Circle[10]; Array of objects: array of reference variables. Invoking circleArray[1].getArea() involves two levels of referencing. circleArray references to the entire array. circleArray[1] references to a Circle object.

Array of Objects, cont. Circle[] circleArray = new Circle[10];

Summarizing the areas of the circles Array of Objects, cont. Summarizing the areas of the circles TotalArea Run

Packages Manage complexity of applications Software reuse – import Unique class names Import classes that are in a different package.

Packages Definition: Compilation (with directory setup) Usage: package package_name; //first line of code The class file is stored in package_name Compilation (with directory setup) Javac –d directory_above_package source_file Usage: import package_name;