• No results found

class & object.ppt

N/A
N/A
Protected

Academic year: 2020

Share "class & object.ppt"

Copied!
42
0
0

Loading.... (view fulltext now)

Full text

(1)

Chapter 6 Objects and Classes

Working of java

OO Programming Concepts

Creating Objects and Object Reference Variables

Differences between primitive data type and object type

Automatic garbage collection

Constructors

Modifiers (

public

,

private

and

static

)

Instance and Class Variables and Methods

(2)
(3)

OO Programming Concepts

data field 1

method n data field n

method 1 An object

...

...

State

Behavior

Data Field radius = 5

(4)

JAVA Classes

The class is the fundamental concept in JAVA (and other

OOPLs)

A class describes some data object(s), and the operations

(or methods) that can be applied to those objects

Every object and method in Java belongs to a class

Classes have data (fields) and code (methods) and classes

(member classes or inner classes)

Static methods and fields belong to the class itselfOthers belong to instances

(5)

Class and Objects

circle1: Circle

radius = 2 new Circle()

circlen: Circle

radius = 5

new Circle()

...

UML Graphical notation for classes

UML Graphical notation for objects

Circle

radius: double

findArea(): double

(6)

Class Declaration

class Circle {

double radius = 1.0;

double findArea(){

return radius * radius * 3.14159;

}

(7)

Declaring Object Reference Variables

ClassName objectReference;

Example:

(8)

Creating Objects

objectReference = new ClassName();

Example:

myCircle = new Circle();

(9)

Declaring/Creating Objects

in a Single Step

ClassName

objectReference

= new

ClassName();

Example:

(10)

Differences between variables of

primitive Data types and object types

1

c: Circle

radius = 1

Primitive type

int i = 1 i

Object type

Circle c c

reference

Created using

new Circle()

(11)

Copying Variables of Primitive Data

Types and Object Types

1

c1: Circle

radius = 5

Primitive type assignment i = j

Before: i 2 j 2 After: i 2 j

Object type assignment c1 = c2

Before: c1 c2 After: c1 c2 c2: Circle

(12)

Garbage Collection

As shown in the previous

figure, after the assignment

statement c1 = c2, c1 points to

the same object referenced by

c2. The object previously

referenced by c1 is no longer

useful. This object is known as

garbage. Garbage is

(13)

Garbage Collection, cont

TIP: If you know that an

object is no longer needed,

you can explicitly assign

null to a reference

variable for the object.

The Java VM will

(14)

Accessing Objects

Referencing the object’s data:

objectReference.data

myCircle.radius

Invoking the object’s method:

objectReference.method

(15)

Constructors

• Classes should define one or more methods to create or construct instances of the class

Their name is the same as the class name

– note deviation from convention that methods begin with lower case

Constructors are differentiated by the number and types of

their arguments

– An example of overloading

If you don’t define a constructor, a default one will be

created.

Constructors automatically invoke the zero argument

constructor of their superclass when they begin (note that this yields a recursive process!)

(16)

Constructors

Circle(double r) {

radius = r;

}

Circle() {

radius = 1.0;

}

myCircle = new Circle(5.0);

Constructors are a

special kind of

methods that are

(17)

Constructors, cont.

A constructor with no parameters

is referred to as a

default

constructor

.

Constructors must have the

same name as the class itself.

Constructors do not have a

return type—not even void.

Constructors are invoked using

the new operator when an object is

created. Constructors play the

(18)

Visibility Modifiers and

Accessor Methods

By default, the class, variable, or data 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.

(19)

Passing Objects to Methods

Passing by value (the value is the reference

to the object)

(20)

Passing Objects to Methods, cont.

main method Reference myCircle 5

n 5

times printAreas method Reference c myCircle: Circle radius = 1

Pass by value (here the value is 5)

(21)

Instance

Variables, and Methods

Instance variables belong to a specific instance.

(22)

Class Variables, Constants,

and Methods

Class variables are shared by all the instances of the

class.

Class methods are not tied to a specific object.

Class constants are final variables shared by all the

instances of the class.

(23)

Scope of Variables

The scope of instance and class variables is the

entire class. They can be declared anywhere

inside a class.

The scope of a local variable starts from its

(24)

The static keyword

Java methods and variables can be declared static

These exist

independent of any object

This means that a Class’s

static methods can be called even if no objects of that

class have been created and

static data is “shared” by all instances (i.e., one rvalue

per class instead of one per instance

24

class StaticTest {static int i = 47;} StaticTest st1 = new StaticTest(); StaticTest st2 = new StaticTest(); // st1.i == st2.I == 47

(25)

Methods

A method is a named sequence of code that can be invoked

by other Java code.

A method takes some parameters, performs some

computations and then optionally returns a value (or object).

Methods can be used as part of an expression statement.

public float convertCelsius(float tempC) {

(26)

Method Signatures

A method signature specifies:

The name of the method.

– The type and name of each parameter.

The type of the value (or object) returned by the method. – The checked exceptions thrown by the method.

Various method modifiers.

modifiers type name ( parameter list ) [throws exceptions ]

public float convertCelsius (float tCelsius ) {}

(27)

Methods, arguments and return values

Java methods are like C/C++ functions. General case:

returnType methodName ( arg1, arg2, … argN) { methodBody

}

The return keyword exits a method optionally with a value

int storage(String s) {return s.length() * 2;} boolean flag() { return true; }

float naturalLogBase() { return 2.718f; } void nothing() { return; }

void nothing2() {}

(28)

Simple Class and Method

Class

Fruit

{

int

grams

;

int

cals_per_gram

;

int

total_calories

() {

return(

grams

*

cals_per_gram

);

}

(29)

Command Line Arguments

C:\UMBC\331\java>type echo.java

// This is the Echo example from the Sun tutorial

class echo {

public static void main(String args[]) { for (int i=0; i < args.length; i++) { System.out.println( args[i] );

} }}

C:\UMBC\331\java>javac echo.java

C:\UMBC\331\java>java echo this is pretty silly this

is

(30)

Arrays

Am array is a list of similar thingsAn array has a fixed:

name

type

length

These must be declared when the array is created.

Arrays sizes cannot be changed during the execution of the

(31)

myArray has room for 8 elements

the elements are accessed by their index

in Java, array indices start at 0

3

6

3

1

6

3

4

1

myArray =

(32)

Declaring Arrays

int myArray[];

declares

myArray

to be an array of integers

myArray =

new

int[8];

sets up 8 integer-sized spaces in memory, labelled

myArray[0]

to

myArray[7]

int

myArray[] =

new

int[8];

(33)

Declaring the Array

1. Declare the array

private Student studentList[];

this declares studentList

2 .Create the array

studentList =

new

Student[10];

this sets up 10 spaces in memory that can

hold references to Student objects

3. Create Student objects and add them to the array:

(34)

Assigning Values

refer to the array elements by index to store values in them.

myArray[0] = 3;

myArray[1] = 6;

myArray[2] = 3;

...

can create and initialise in one step:

(35)

Iterating Through Arrays

for

loops are useful when dealing with arrays:

for (int i = 0; i < myArray.length;

i++) {

(36)

Array of Objects

Circle[] circleArray = new

Circle[10];

An array of objects is actually

an array of reference variables

.

So invoking

circleArray[1].findArea() involves

two levels of referencing as

shown in the next figure.

circleArray references to the

entire array. circleArray[1]

(37)

Array of Objects, cont.

Circle[] circleArray = new

Circle[10];

reference circleArray[0] Circle object 0

circleArray

circleArray[1]

(38)

Class Abstraction

Class abstraction means to separate class

implementation from the use of the class. The

creator of the class provides a description of the

class and let the user know how the class can be

used. The user of the class does not need to

(39)

Java API and Core Java classes

java.lang

Contains core Java classes, such as numeric

classes, strings, and objects. This package is

implicitly imported to every Java program.

java.awt

Contains classes for graphics.

java.applet

(40)

java.io

Contains classes for input and output

streams and files.

java.util

Contains many utilities, such as date.

java.net

Contains classes for supporting

network communications.

(41)

java.awt.image

Contains classes for managing bitmap images.

java.awt.peer

Platform-specific GUI implementation.

Others:

java.sql

java.rmi

(42)

Java Development Kit

javac

- The Java Compiler

java

- The Java Interpreter

jdb

- The Java Debugger

appletviewer

-Tool to run the applets

javap - to print the Java bytecodes

javaprof - Java profiler

javadoc - documentation generator

References

Related documents

Java Program (MyProgram.java) Java Compiler (javac) Java Bytecode (MyProgram.class) HW-based Platform (Sun + Solaris OS) Java API. Interpreter or

The VX Cycle offers a broad range of scales for the cost-effective production of LNG/CCNG, and the Cycle can be integrated with existing CNG stations, pipeline compressor stations

Judith Kates is Professor of Jewish Women's Studies at Hebrew College, currently teaching Bible and Jewish traditions of commentary for the new Rabbinical School

Given the restricted use of e-signatures to include internal use only and the requirement that all users must be authenticated to the Authority domain for an e-signature to be

A microcontroller is used to control the illumination provided by the PPG sensor and the capture of the reflected signals, as shown in Figure 3.4.1 The lighting is synchronized for

The results presented indicate that the high volatile acid pro- duction of starters is not the result of mixtures of two or more cultures of Bact. PRESENCE IN

There are many augmented reality (AR) applications avail- able that can be used to create educational contents for these mobile devices. This paper surveys the most popular

(B) the adsorption at a single site on the surface may involve multiple molecules at the same time.. (C) the mass of gas striking a given area of surface is proportional to the