Classes methods objects
Download
1 / 68

Classes, Methods, & Objects - PowerPoint PPT Presentation


  • 119 Views
  • Uploaded on

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

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about ' Classes, Methods, & Objects' - kedem


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

Objectives
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

  • Learn how parameters are passed to constructors and methods and how to return values from methods

  • Learn about static and instance fields and methods

  • Learn about method overloading.

  • Learn about the copy constructor.

  • Learn about encapsulation .


Terminology
Terminology

  • Class – is a model, pattern, or blueprint from which an object is created. A class describes the objects, their structure and behavior

  • Instance 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.


Class
Class

  • Declared public

  • Keyword class

  • Class 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


Classes and source files
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 .java

  • The Java files for all the classes you create for a project should be located in the same folder.


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.


Class s client
Class’s Client

  • Any class that uses class X is called a client of X

Class X

private fields

private methods

Class Y

A client of X

public constructor(s)

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

public methods


Fields
Fields

  • Fields – data elements of the class.

  • Fields may hold numbers, characters, strings, or objects

  • Fields 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.


Fields1
Fields

  • Fields are declared as private or public. In most cases, they are declared private

  • When 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 intmySum = 10;

    • private static intmySum = 10; //creates one memory location that all the objects share

  • Fields are Global meaning that they can be accessed anywhere in the class including methods.


Access modifiers public and private
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.


Public vs private
Public vs. Private

  • Public 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.


Public vs private cont d
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

{

privateint num, denom;

...

public multiply (Fraction other)

{

intnewNum = num * other.num;

...


Encapsulation
Encapsulation

  • Hiding 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.


Encapsulation cont d
Encapsulation (cont’d)

public class MyClass

{

// Private fields:

private <sometype> myField;

...

// Constructors:

publicMyClass (...) { ... }

...

// Public methods:

public <sometype> myMethod (...)

{ ... }

...

// Private methods:

private <sometype> myMethod (...)

{ ... }

...

}

Public interface: public constructors and methods


Constructors
Constructors

  • Constructor 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 parameters

  • Constructors are not called explicitly, but invoked using the new operator.


Constructors1
Constructors

  • Has 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


Constructor
Constructor

  • If 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.


Constructors cont d
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.


Constructors cont d1
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


Constructors cont d2
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.


Constructors cont d3
Constructors (cont’d)

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

public class Fraction

{

...

public Fraction (int n)

{

this (n, 1);

}

...

...

public Fraction (int p, int q)

{

num = p;

denom = q;

reduce ();

}

...


Copy constructor
Copy Constructor

  • Student s1 = new Student();

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


Notes
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.


Methods
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.


Method design
Method Design

  • An algorithm is a step-by-step process for solving a problem

  • Examples: a recipe, travel directions

  • Every method implements an algorithm that determines how the method accomplishes its goals

  • An algorithm may be expressed in pseudocode, a mixture of code statements and English that communicate the steps to take


Method decomposition
Method Decomposition

  • A method should be relatively small, so that it can be understood as a single entity

  • A potentially large method should be decomposed into several smaller methods as needed for clarity

  • A public service method of an object may call one or more private support methods to help it accomplish its goal

  • Support methods might call other support methods if appropriate


Accessors and modifiers
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.


Methods1
Methods

public [or private] returnTypemethodName(type1 name1, ...,typeNnameN)

{

...

}

  • 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

Body

Header


Methods cont d
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.

Empty parentheses indicate that a method takes no parameters

public [or private] returnTypemethodName( )

{ ... }


Methods java style
Methods: Java Style

  • A 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, getX

  • The name of a method that sets the value of a field often starts with set:

    setLocation, setText


Static fields and methods
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.


Static fields
Static Fields

  • static 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.


Static fields continued
Static fields continued

  • Static 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;


Static fields1
Static Fields

  • A 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.


Static fields cont d
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:

static

final


Static fields cont d1
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);


Static fields cont d2
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.


Static methods
Static Methods

  • Static 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);


Static methods cont d
Static Methods (cont’d)

public class MyClass

{

public static final intstatConst;

private staticintstatVar;

private intinstVar;

...

public staticintstatMethod(...)

{

statVar = statConst;

statMethod2(...);

instVar = ...;

instMethod(...);

}

Static method

OK

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


Static methods cont d1
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)


Static methods1
Static Methods

class Helper

{

public static int cube (int num)

{

return num * num * num;

}

}

Because it is declared as static, the method

can be invoked as

value = Helper.cube(5);


Static class members
Static Class Members

  • The 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 object

  • Static methods cannot reference instance variables because instance variables don't exist until an object exists

  • However, a static method can reference static variables or local variables


Oop model
OOP Model

  • OOP 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.


Operator new
Operator new

  • Constructors 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.

public class Fraction

{

public Fraction (int n)

{

num = n;

denom = 1;

}

...

  • Fraction f1 = new Fraction ( );

  • Fraction f2 = new Fraction (5);

  • Fraction f3 = new Fraction (4, 6);

  • Fraction f4 = new Fraction (f3);

5 / 1


Operator new cont d
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);

ratio is set to null

Now ratio refers to a valid object

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


References to objects

f1

f1

A Fraction

object:

num = 3

denom = 7

A Fraction

object:

num = 3

denom = 7

A Fraction

object:

num = 3

denom = 7

f2

References to Objects

Fraction f1 = new Fraction(3,7);

Fraction f2 = new Fraction(3,7);

Fraction f1 = new Fraction(3,7);

Fraction f2 = f1;

f2

Refer to the same object


Passing parameters to constructors and methods
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) { ... }

...


Passing parameters cont d
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:

...

Polynomial p = new Polynomial (1, -5, 6);

double y = p.getValue (3);

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

The same as: (3.0)


Passing parameters cont d1
Passing Parameters (cont’d)

  • Primitive data types are always passed “by value”: the value is copied into the parameter.

public class Polynomial

{

...

public double getValue (double u)

{

double v;

...

}

}

copy

double x = 3.0;

double y = p.getValue ( x );

u acts like a local variable in getValue

x: 3.0

u:3.0

copy


Passing parameters cont d2
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


Passing parameters cont d3

A Fraction

object:

num = 5

denom = 17

Passing Parameters (cont’d)

  • Objects are always passed as references: the reference is copied, not the object.

public class Fraction

{

...

public Fraction add

(Fraction f)

{

...

}

}

Fraction f1 = new Fraction (1, 2);

Fraction f2 = new Fraction (5, 17);

Fraction f3 = f1.add (f2);

copy reference

refersto

refers to the same object


Passing parameters cont d4
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);


Passing parameters cont d5
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


Return statement
return Statement

  • A 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:

returnexpression;

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


Return statement cont d
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 someTypemyMethod (...)

{

...

if (...)

return <expression1>;

else if (...)

return <expression2>;

...

return <expression3>;

}


Return statement cont d1
return Statement (cont’d)

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

public booleanmyMethod (...)

{

...

if (...)

return true;

...

return n % 2 == 0;

}


Return statement cont d2
return Statement (cont’d)

  • A void method can use a return statement to quit the method early:

public voidmyMethod (...)

{

...

if (...)

return;

...

}

No need for a redundant return at the end


Return statement cont d3
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);

}


Overloaded methods
Overloaded Methods

  • Methods 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) { ... }


Overloaded methods cont d
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.

public class Circle

{

public void move(intx, int y)

{ ... }

public void move (Point p)

{ ... }

...

Circle circle = new Circle(5);

circle.move (50, 100);

Point center = new Point(50, 100);

circle.move (center);


Overloaded methods cont d1
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


Objects as parameters
Objects as Parameters

  • Another important issue related to method design involves parameter passing

  • Parameters 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 statement

  • When an object is passed to a method, the actual parameter and the formal parameter become aliases of each other


Method overloading
Method Overloading

  • Method overloading is the process of giving a single method name multiple definitions

  • If a method is overloaded, the method name is not sufficient to determine which method is being called

  • The signature of each overloaded method must be unique

  • The signature includes the number, type, and order of the parameters


Method overloading1

Invocation

result = tryMe(25, 4.32)

Method Overloading

  • The 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;

}


Method overloading2
Method Overloading

  • Theprintlnmethod is overloaded:

    println (String s)

    println (inti)

    println (double d)

    and so on...

  • The following lines invoke different versions of theprintlnmethod:

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

    System.out.println (total);


Overloading methods
Overloading Methods

  • The return type of the method is not part of the signature

  • That is, overloaded methods cannot differ only by their return type

  • Constructors can be overloaded

  • Overloaded constructors provide multiple ways to initialize a new object


Summary
Summary

  • Methods 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)


Summary1
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


ad