Classes, Methods, & Objects

68
Classes, Methods, & Objects

description

Classes, Methods, & Objects. Objectives. Review public and private fields and methods Learn the syntax for defining constructors and creating objects Learn the syntax for defining and calling methods - PowerPoint PPT Presentation

Transcript of Classes, Methods, & Objects

Page 1: Classes, Methods, & Objects

Classes, Methods, & Objects

Page 2: Classes, Methods, & Objects

ObjectivesReview public and private fields and methodsLearn the syntax for defining constructors and creating objectsLearn the syntax for defining and calling methodsLearn how parameters are passed to constructors and methods and how to return values from methods

Learn about static and instance fields and methodsLearn about method overloading.Learn about the copy constructor.Learn about encapsulation .

Page 3: Classes, Methods, & Objects

TerminologyClass – is a model, pattern, or blueprint from which an object is created. A class describes the objects, their structure and behaviorInstance data or variable (fields) – memory space is created for each instance of the class that is created. Variables declared in a class.When you create an object, you are creating an instance of a class. (Copy of the class)Method – subprograms that perform a specific task. 2 parts of a method:– Method Declaration – access level(public or

private), return type, name, and parameters. – Method Body – local variable declaration,

statements that implements the method.

Page 4: Classes, Methods, & Objects

ClassDeclared publicKeyword classClass name (1st letter of name should be capitalized)Begin Brace {Example:public class Student{

When saving a class, it should be saved as the same name as class with the extension .java

Page 5: Classes, Methods, & Objects

Classes and Source Files

The name of the source file must be exactly the same name as the class (including upper and lowercase letters) with the extension .javaThe Java files for all the classes you create for a project should be located in the same folder.

Page 6: Classes, Methods, & Objects

Objects

In a well designed OOP program, each object is responsible for its own clearly defined set of tasks. Objects must be easily controlled and not too complicated.

Page 7: Classes, Methods, & Objects

Class’s ClientAny class that uses class X is called a client of XClass Xprivate fields

private methods

public methods

public constructor(s)

Class Y

A client of X

Constructs objects of X and/or calls X’s methods

Page 8: Classes, Methods, & Objects

FieldsFields – data elements of the class.Fields may hold numbers, characters, strings, or objectsFields act as personal memory of an object and the particular values stored in them determine the object’s current state.Each object (instance of a class) has the same fields, but there may be different values stored in those fields.

Page 9: Classes, Methods, & Objects

FieldsFields are declared as private or public. In most cases, they are declared privateWhen each variable is created for each object of the class, it is called instance variable.When a field is declared as static, it is called a class variable and only created once and all objects share that memory location.Examples:– private int mySum = 10;– private static int mySum = 10; //creates one

memory location that all the objects shareFields are Global meaning that they can be accessed anywhere in the class including methods.

Page 10: Classes, Methods, & Objects

Access Modifiers public and private

Variables or methods declared with access modifier private are accessible only to methods of the class in which they are declared. Public variables or methods can be accessible from outside the class.Data Hiding (encapsulated) – The private access modifier allows a programmer to hide memory location from the program and can’t be directly changed.

Page 11: Classes, Methods, & Objects

Public vs. PrivatePublic constructors and methods of a class constitute its interface with classes that use it — its clients.All fields are usually declared private — they are hidden from clients.Static constants occasionally can be public.“Helper” methods that are needed only inside the class are declared private.

Page 12: Classes, Methods, & Objects

Public vs. Private (cont’d)A private field is accessible anywhere within the class’s source code.Any object can access and modify a private field of another object of the same class.

public class Fraction{ private int num, denom; ... public multiply (Fraction other) { int newNum = num * other.num; ...

Page 13: Classes, Methods, & Objects

EncapsulationHiding the implementation details of a class (making all fields and helper methods private) is called encapsulation.Encapsulation helps in program maintenance: a change in one class does not affect other classes.A client of a class iteracts with the class only through well-documented public constructors and methods; this facilitates team development.

Page 14: Classes, Methods, & Objects

Encapsulation (cont’d) public class MyClass { // Private fields: private <sometype> myField; ...

// Constructors: public MyClass (...) { ... } ... // Public methods: public <sometype> myMethod (...) { ... } ... // Private methods: private <sometype> myMethod (...) { ... } ... }

Public interface: public constructors and methods

Page 15: Classes, Methods, & Objects

ConstructorsConstructor primary purpose is to initialize the object’s field.A class’s constructor define different ways of creating an object.Different constructor use different numbers or types of parametersConstructors are not called explicitly, but invoked using the new operator.

Page 16: Classes, Methods, & Objects

ConstructorsHas the same name as the class.Default constructor – automatically created by the compiler if no constructors are present.Default constructor assigns the fields to all default values if they are not initialized.– Default values – integers and real data fields are set

to 0.– Objects are set to null– Boolean – are set to false

Constructors do not have a return type

Page 17: Classes, Methods, & Objects

ConstructorIf a class has more than one constructor, they must have different numbers and/or types of parameters.Constructors allows you to create a set the fields to their starting values.One of the constructors will run when an object of the class is created.

Page 18: Classes, Methods, & Objects

Constructors (cont’d)Programmers often provide a “no-args” constructor that takes no parameters (a.k.a. arguments).If a programmer does not define any constructors, Java provides one default no-args constructor, which allocates memory and sets fields to the default values.

Page 19: Classes, Methods, & Objects

Constructors (cont’d)public class Fraction{ private int num, denom;

public Fraction ( ) { num = 0; denom = 1; }

public Fraction (int n) { num = n; denom = 1; } Continued

public Fraction (int n, int d) { num = n; denom = d; reduce (); }

public Fraction (Fraction other) { num = other.num; denom = other.denom; } ...

}

“No-args” constructor

Copy constructor

Page 20: Classes, Methods, & Objects

Constructors (cont’d)A nasty bug:

public class MyWindow extends JFrame{ ... // Constructor: public void MyWindow ( ) { ... } ...

Compiles fine, but the compiler thinks this is a method and uses MyWindow’s default no-args constructor instead because of void being there.

Page 21: Classes, Methods, & Objects

Constructors (cont’d)

Constructors of a class can call each other using the keyword this — a good way to avoid duplicating code:

... public Fraction (int p, int q) { num = p; denom = q; reduce (); } ...

public class Fraction{ ...

public Fraction (int n) { this (n, 1); } ...

Page 22: Classes, Methods, & Objects

Copy ConstructorStudent s1 = new Student();Student s2 = new Student(s1); //copy constructor.

Page 23: Classes, Methods, & Objects

Notes

Dynamic Memory Allocation – pool of memory that is drawn from and added to as the program is running.Garbage Collection – When the computer is done with an object, it is put into the garbage collection.Variables holds a reference (address) to an object of the corresponding type.It is crucial to initialize a reference before using it.

Page 24: Classes, Methods, & Objects

Methods

Methods – defines the behavior of an object, what the object can do.It represents what an object of a particular type can do in response to a particular call or message.

Page 25: Classes, Methods, & Objects

Method Design

An algorithm is a step-by-step process for solving a problemExamples: a recipe, travel directionsEvery method implements an algorithm that determines how the method accomplishes its goalsAn algorithm may be expressed in pseudocode, a mixture of code statements and English that communicate the steps to take

Page 26: Classes, Methods, & Objects

Method Decomposition

A method should be relatively small, so that it can be understood as a single entityA potentially large method should be decomposed into several smaller methods as needed for clarityA public service method of an object may call one or more private support methods to help it accomplish its goalSupport methods might call other support methods if appropriate

Page 27: Classes, Methods, & Objects

Accessors and Modifiers

A programmer often provides methods, called accessors, that return values of private fields; methods that set values of private fields are called modifiers (Mutator).Accessors’ names often start with get, and modifiers’ names often start with set.These are not precise categories: the same method can modify several fields or modify a field and also return its old or new value.

Page 28: Classes, Methods, & Objects

Methods

To define a method:– decide between public and private (usually

public)– give it a name– specify the types of parameters and give

them names– specify the method’s return type or chose

void– write the method’s code

public [or private] returnType methodName (type1 name1, ...,typeN nameN){ ...}

HeaderBody

Page 29: Classes, Methods, & Objects

Methods (cont’d)A method is always defined inside a class.A method returns a value of the specified type unless it is declared void; the return type can be any primitive data type or a class type.A method’s parameters can be of any primitive data types or class types.

public [or private] returnType methodName ( ){ ... }

Empty parentheses indicate that a method takes no parameters

Page 30: Classes, Methods, & Objects

Methods: Java StyleA method name starts with a lowercase letter.Method names usually sound like verbs.The name of a method that returns the value of a field often starts with get:

getWidth, getXThe name of a method that sets the value of a field often starts with set:

setLocation, setText

Page 31: Classes, Methods, & Objects

Static Fields and methods

Two types of variables– Instance variables – non-static – Class variable – static

Static fields are called static because their memory is not dynamically allocated. Memory for static fields is reserved even before any object of the class have been created. Static methods are not allowed to access or set any non-static methods of the same class.Instance methods (non-static) can access and change both static and non-static fields.

Page 32: Classes, Methods, & Objects

Static Fieldsstatic fields are shared by all instance of the class.Example: private static final String letters =“ABCD”;Static fields are stored separately from instance of the class in a special memory space allocated for the class as a whole.

Page 33: Classes, Methods, & Objects

Static fields continuedStatic simply saves space in memory.The code for methods is not duplicated either: all instances of the same class share code for its method. All final variables should be declared static because there is no reason to duplicate them.Example:Private static final int sum = 8;

Page 34: Classes, Methods, & Objects

Static FieldsA static field (a.k.a. class field or class variable) is shared by all objects of the class.A non-static field (a.k.a. instance field or instance variable) belongs to an individual object.

Page 35: Classes, Methods, & Objects

Static Fields (cont’d)A static field can hold a constant shared by all objects of the class:

A static field can be used to collect statistics or totals for all objects of the class (for example, total sales for all vending machines)

public class RollingDie{ private static final double slowDown = 0.97; private static final double speedFactor = 0.04; ...

Reserved words:staticfinal

Page 36: Classes, Methods, & Objects

Static Fields (cont’d)Static fields are stored with the class code, separately from instance variables that describe an individual object.Public static fields, usually global constants, are referred to in other classes using “dot notation”: ClassName.constName

double area = Math.PI * r * r;setBackground(Color.BLUE);c.add(btn, BorderLayout.NORTH);System.out.println(area);

Page 37: Classes, Methods, & Objects

Static Fields (cont’d)Usually static fields are NOT initialized in constructors (they are initialized either in declarations or in public static methods).If a class has only static fields, there is no point in creating objects of that class (all of them would be identical).Math and System are examples of the above. They have no public constructors and cannot be instantiated.

Page 38: Classes, Methods, & Objects

Static MethodsStatic methods can access and manipulate a class’s static fields.Static methods cannot access non-static fields or call non-static methods of the class.Static methods are called using “dot notation”: ClassName.statMethod(...)

double x = Math.random(); double y = Math.sqrt (x);

Page 39: Classes, Methods, & Objects

Static Methods (cont’d)public class MyClass{ public static final int statConst; private static int statVar; private int instVar; ... public static int statMethod(...) { statVar = statConst; statMethod2(...);

instVar = ...; instMethod(...); }

Errors! instVar &instMethod are not a static variable or Method

OK

Static method

Page 40: Classes, Methods, & Objects

Static Methods (cont’d)

main is static and therefore cannot access non-static fields or call non-static methods of its class:

public class Hello{ private int test () { ... }

public static void main (String[ ] args) { System.out.println (test ()); }}

Error:non-static method test is called from static context (main)

Page 41: Classes, Methods, & Objects

Static Methodsclass Helper{ public static int cube (int num) { return num * num * num; }}

Because it is declared as static, the methodcan be invoked as

value = Helper.cube(5);

Page 42: Classes, Methods, & Objects

Static Class MembersThe order of the modifiers can be interchanged, but by convention visibility modifiers come first Recall that the main method is static – it is invoked by the Java interpreter without creating an objectStatic methods cannot reference instance variables because instance variables don't exist until an object existsHowever, a static method can reference static variables or local variables

Page 43: Classes, Methods, & Objects

OOP ModelOOP program maintains a world of interacting objects– Describe the different types of objects– What they can do– How they are created– How they interact with other objects.

Page 44: Classes, Methods, & Objects

Operator newConstructors are invoked using the operator new.Parameters passed to new must match the number, types, and order of parameters expected by one of the constructors.

Fraction f1 = new Fraction ( );Fraction f2 = new Fraction (5);Fraction f3 = new Fraction (4, 6);Fraction f4 = new Fraction (f3);

public class Fraction{ public Fraction (int n) { num = n; denom = 1; } ...

5 / 1

Page 45: Classes, Methods, & Objects

Operator new (cont’d)You must create an object before you can use it; the new operator is a way to do it.private Fraction ratio;

... ratio = new Fraction (2, 3);

...ratio = new Fraction (3, 4);

Now ratio refers to another object (the old object is “garbage-collected”)

Now ratio refers to a valid object

ratio is set to null

Page 46: Classes, Methods, & Objects

References to ObjectsFraction f1 = new Fraction(3,7);Fraction f2 = f1;

Fraction f1 = new Fraction(3,7);Fraction f2 = new Fraction(3,7);

A Fraction object:num = 3denom = 7

A Fraction object:num = 3denom = 7

A Fraction object:num = 3denom = 7

f1

f2

f1

f2

Refer to the same object

Page 47: Classes, Methods, & Objects

Passing Parameters to Constructors and Methods

Any expression that has an appropriate data type can serve as a parameter:

double u = 3, v = -4; ... Polynomial p = new Polynomial (1.0, -(u + v), u * v); double y = p.getValue (2 * v - u);

public class Polynomial{ public Polynomial (double a, double b, double c) { ... } public double getValue (double x) { ... } ...

Page 48: Classes, Methods, & Objects

Passing Parameters (cont’d)

A “smaller” type can be promoted to a “larger” type (for example, int to long, float to double).int is promoted to double when necessary:

The same as: (3.0)

... Polynomial p = new Polynomial (1, -5, 6); double y = p.getValue (3);

The same as: (1.0, -5.0, 6.0)

Page 49: Classes, Methods, & Objects

Passing Parameters (cont’d)Primitive data types are always passed “by value”: the value is copied into the parameter.

double x = 3.0; double y = p.getValue ( x );

public class Polynomial{ ... public double getValue (double u) { double v; ... }}

x: 3.0 u:

3.0copy

copy

u acts like a local variable in getValue

Page 50: Classes, Methods, & Objects

Passing Parameters (cont’d)public class Test{ public double square (double x) { x *= x; return x; }

public static void main(String[ ] args) { Test calc = new Test (); double x = 3.0; double y = calc.square (x); System.out.println (x + " " + y); }}

x here is a copy of the parameter passed to square. The copy is changed, but...

... the original x is unchanged.Output: 3 9

Page 51: Classes, Methods, & Objects

Passing Parameters (cont’d)Objects are always passed as references: the reference is copied, not the object.

Fraction f1 = new Fraction (1, 2); Fraction f2 = new Fraction (5, 17);

Fraction f3 = f1.add (f2);

public class Fraction{ ... public Fraction add (Fraction f) { ... }}

copy reference

A Fraction object:num = 5denom = 17

refers to the same

object

refers to

Page 52: Classes, Methods, & Objects

Passing Parameters (cont’d)A method can change an object passed to it as a parameter (because the method gets a reference to the original object).A method can change the object for which it was called (this object acts like an implicit parameter):

panel.setBackround(Color.BLUE);

Page 53: Classes, Methods, & Objects

Passing Parameters (cont’d)Inside a method, this refers to the object for which the method was called. this can be passed to other constructors and methods as a parameter: public class ChessGame

{ ... Player player1 = new Player (this); ...

A reference to this ChessGame object

Page 54: Classes, Methods, & Objects

return StatementA method, unless void, returns a value of the specified type to the calling method.The return statement is used to immediately quit the method and return a value: return expression;

The type of the return value or expression must match the method’s declared return type.

Page 55: Classes, Methods, & Objects

return Statement (cont’d)A method can have several return statements; then all but one of them must be inside an if or else (or in a switch): public someType myMethod (...)

{ ... if (...) return <expression1>; else if (...) return <expression2>; ... return <expression3>;}

Page 56: Classes, Methods, & Objects

return Statement (cont’d)

A boolean method can return true, false, or the result of a boolean expression:

public boolean myMethod (...){ ... if (...) return true; ... return n % 2 == 0;}

Page 57: Classes, Methods, & Objects

return Statement (cont’d)A void method can use a return statement to quit the method early:

public void myMethod (...){ ... if (...) return; ...} No need for a

redundant return at the end

Page 58: Classes, Methods, & Objects

return Statement (cont’d)If its return type is a class, the method returns a reference to an object (or null).Often the returned object is created in the method using new. For example:

The returned object can also come from a parameter or from a call to another method.

public Fraction inverse () { if (num == 0) return null; return new Fraction (denom, num); }

Page 59: Classes, Methods, & Objects

Overloaded MethodsMethods of the same class that have the same name but different numbers or types of parameters are called overloaded methods.Use overloaded methods when they perform similar tasks:

public void move (int x, int y) { ... }public void move (double x, double y) { ... }public void move (Point p) { ... }

public Fraction add (int n) { ... }public Fraction add (Fraction other) { ... }

Page 60: Classes, Methods, & Objects

Overloaded Methods (cont’d)The compiler treats overloaded methods as completely different methods.The compiler knows which one to call based on the number and the types of the parameters passed to the method.

9-60

Circle circle = new Circle(5);circle.move (50, 100);Point center = new Point(50, 100);circle.move (center);

public class Circle{ public void move(int x, int y) { ... }

public void move (Point p) { ... } ...

Page 61: Classes, Methods, & Objects

Overloaded Methods (cont’d)The return type alone is not sufficient for distinguishing between overloaded methods.

public class Circle{ public void move (int x, int y) { ... }

public Point move (int x, int y) { ... } ...

Syntax error

Page 62: Classes, Methods, & Objects

Objects as ParametersAnother important issue related to method design involves parameter passingParameters in a Java method are passed by value

A copy of the actual parameter (the value passed in) is stored into the formal parameter (in the method header)Therefore passing parameters is similar to an assignment statementWhen an object is passed to a method, the actual parameter and the formal parameter become aliases of each other

Page 63: Classes, Methods, & Objects

Method OverloadingMethod overloading is the process of giving a single method name multiple definitionsIf a method is overloaded, the method name is not sufficient to determine which method is being calledThe signature of each overloaded method must be uniqueThe signature includes the number, type, and order of the parameters

Page 64: Classes, Methods, & Objects

Method OverloadingThe compiler determines which method is being invoked by analyzing the parameters

float tryMe(int x){ return x + .375;}

float tryMe(int x, float y){ return x*y;}

result = tryMe(25, 4.32)

Invocation

Page 65: Classes, Methods, & Objects

Method OverloadingThe println method is overloaded:

println (String s) println (int i) println (double d)

and so on...The following lines invoke different versions of the println method:

System.out.println ("The total is:"); System.out.println (total);

Page 66: Classes, Methods, & Objects

Overloading MethodsThe return type of the method is not part of the signatureThat is, overloaded methods cannot differ only by their return typeConstructors can be overloadedOverloaded constructors provide multiple ways to initialize a new object

Page 67: Classes, Methods, & Objects

SummaryMethods define the functionality of an object.A method is basically a fragment of code that implements a certain task or computation and that is callable from other methods in the program.All objects in a class SHARE the same set of methods.A method is usually called for a particular object of the class (except for static method discussed later)

Page 68: Classes, Methods, & Objects

Summary

Methods can be designated public or private.

Public methods can be called from any other class.

Private methods can be called only from other methods of the same class.

Parameters is a list in parentheses of a method.

Arguments values in the parentheses when the method is called or invoked