0% found this document useful (0 votes)
13 views

03 Chapter Three - Objects and Classe

Uploaded by

dagid6944
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

03 Chapter Three - Objects and Classe

Uploaded by

dagid6944
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 73

Chapter Three

OBJECTS AND
CLASSES
OUTLINE
 Object and Class

 Creating object
 Instantiating and using object
 Instance fields
 Constructor and Methods
 Access Modifier
 Encapsulation
CLASS
 class is the fundamental that paves the way for object-oriented
programming
 class is a group of objects which have common properties
 class is a blueprint for creating objects (instances)
 It defines the state and behaviors (attributes and methods) that
objects of that class will have
 It is a template or blueprint from which individual objects are
created.
CONT …
 It is a user-defined data type that can be accessed and
used by creating an instance of that class.
 It has its own data members and member functions.
 Both member functions and data members are found
in classes.
 The data members inside the class are manipulated
using these member functions.
OBJECT
Objects are key to understanding object-oriented technology.
 It can be physical or logical (tangible and intangible).
 Examples of real-world objects: your cat, your desk, your
television set, your bicycle, laptop, dog, car etc.
Real world object has two characteristics:
 State: represents the data (value) of an object.
 Behavior: represents the behavior (functionality) of an object.
Object is an instance (result)of a class
SAMPLE PROGRAM- CLASS AND OBJECT

Class Car{ // class car


int size; // state or variable
String color;
Public void setSize(int s){
this.size = s;
}
Public void setColor(String c){ Method/ function= behaviour in real world

this.color = c;
}
// more code goes here
Public static void main(String args []){
Car vanCar = new Car(); // create object1
Car sportCar = new Car(); // create object2
vanCar.setSize(6);
vanCar.setColor(“blue”); assigning value for object
sportCar.setSize(6); sportCar.setColor(“Greye”);
}
DECLARING CLASS

All classes must be defined by a class declaration that provides the name for the class
and the body of the class.

A simplified general form of a class definition is shown here:


[public] class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) { // body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
DECLARING CLASS: DESCRIPTION

public keyword indicates that this class is available for use by other classes.

Although it is optional,

ClassName is an identifier that provides a name for your class.

You can use any identifier you want to name a class but the following three

guidelines can simplify your life:


 Begin the class name with a capital letter.

 If the class name consists of more than one word, begin each word with capital.

 For example, Ball, Car, Dog, Bicycle, RetailCustomer, and GuessingGame.


DECLARING CLASS: DESCRIPTION (2)

 Whenever possible, use nouns for your class names.

 Classes create objects, and nouns are the words you use to

identify objects. Thus, most class names should be nouns.

 Avoid using the name of a Java API class. This is not must, but

if you create a class that has the same name as a Java API class,

you have to use fully qualified names (like java.util.Scanner) to

tell your class and the API class with the same name apart.
INSTANCE VARIABLE IN JAVA
 is created inside the class but outside the method, constructors or any block.

The code is contained within is called methods.

 In most classes, the instance variables are acted upon and accessed by the
methods defined for that class.

Thus, it is the methods that determine how a class’ data can be used.

 Instance variable doesn't get memory at compile time.

It gets memory at runtime when an object or instance is created.

That is why it is known as an instance variable.


A SIMPLE CLASS
Here is a class called Box that defines three instance variables:
width, height, and depth.
class Box { className
double width;
double height; Instance variable
double depth;
}

Currently, Box does not contain any methods .


INSTANTIATING OBJECTS
When you create a class, you are creating a new data type.

You can use this type to declare objects of that type.

However, obtaining objects of a class is a two-step process.

First, you must declare a variable of the class type.

• This variable does not define an object.

• Instead, it is simply a variable that can refer to an object.

Second, you must acquire an actual, physical copy of the object and assign it to that
variable.
 You can do this using the new operator.
INSTANTIATING OBJECTS (2)

The new operator dynamically allocates (that is, allocates at run


time) memory for an object and returns a reference to it.

This reference is, more or less, the address in memory of the


object allocated by new.

This reference is then stored in the variable.

Thus, in Java, all class objects must be dynamically allocated.


INSTANTIATING OBJECTS (3)
Box mybox = new Box();

This statement combines the two steps just described.

It can be rewritten like this to show each step more clearly:

Box mybox; // declare reference to object


mybox = new Box(); // allocate a Box object

The first line declares mybox as a reference to an object of type Box.

 After this line executes, mybox contains the value null, which indicates that it does
not yet point to an actual object.

 Any attempt to use mybox at this point will result in a compile-time error.
ASSIGNING OBJECT REFERENCE
VARIABLES
Object reference variables act differently than you might expect when
an assignment takes place.

For example, what do you think the following fragment does?


Box b1 = new Box();

Box b2 = b1;

You might think that b2 is being assigned a reference to a copy of the


object referred to by b1.

That is, you might think that b1 and b2 refer to separate and distinct
objects.

 However, this would be wrong.


Assigning Object Reference Variables (2)

Instead, after this fragment executes, b1 and b2 will both refer to the

same object.

The assignment of b1 to b2 did not allocate any memory or copy any

part of the original object.

 It simply makes b2 refer to the same object as does b1.

Thus, any changes made to the object through b2 will affect the

object to which b1 is referring, since they are the same object.


ASSIGNING OBJECT REFERENCE
VARIABLES (3)
This situation is depicted Although b1 and b2 both refer to the same object,
they are not linked in any other way.
here:
For example, a subsequent assignment to b1 will
simply unhook b1 from the original object without

 affecting the object or affecting b2. For example:


Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;

Here, b1 has been set to null, but b2 still points to


the original object.
ACCESS LEVEL MODIFIERS

Access level modifiers determine whether external classes can


use a particular field or invoke a particular method of the class
being defined.

There are two levels of access control:


At the top level — public, or package-private (no explicit modifier
specified).

At the member level — public, private, protected or package-private (no


explicit modifier specified).
ACCESS MODIFIERS
Basic type of access modifiers:
 Public: class, methods, variable and constructors can be accessed from any
other class.

 Private: methods, variable and constructor can only be accessed within the
declared class.

 Protected: Methods, variable and constructors are declared protected in a


superclass can be accessed only by the subclasses.

 Default (No modifier): No modifier required

 Access class, variable, method in same package but not from outside.
ACCESS MODIFIERS (2)
The following table shows the access to members permitted by
each modifier.
EXAMPLE

class Rectangle {

public double width;

private double height;

protected double area;

double perimeter; //package-private

}
DATA MEMBERS

A data member is a variable that is defined in the body of a class, outside of


any of the class’ methods.
There are several kinds of variables in classes:
 Fields are available to all the methods of a class.

 Fields are defined the same as any other Java variable, but can have a modifier that
specifies whether the field is public, protected or private.

 If the data member/field specifies the public keyword, then it is visible outside of
the class.

 If you don’t want the field to be visible outside of the class, use the private keyword
instead.

 Field Variable declarations are composed of three components, in order: Zero or


EXAMPLE:
public field declarations
 public int trajectory = 0;
 public String name;
 public int age = 20;

To create a private field, specify private instead of public:


 private int x-position = 0;
 private int y-position = 0;
 private String error-message = “”;

Fields can also be declared as final:


 public final int MAX_SCORE = 1000;

 The value of a final field can’t be changed once it has been initialized.
OTHER MODIFIERS

Static: the variable or method is shared by the entire class.

 can be accessed through the classname instead of just by an instance.

 Final: indicates that it cannot be subclassed.


 For the variable or method, final indicates that it cannot be changed at
runtime or overridden in subclasses.

Abstract: this declaration can apply to classes or methods and indicates that
the class cannot be directly instantiated.
WHAT IS METHOD?
A method is a collection of statements that are grouped together to perform an
operation.

 When you call the System.out.println() method,


 for example, the system actually executes several statements in order to display a
message on the console.

 In another way, method is a block of statements that has a name and can be
executed by calling it from some other place in your program.

 You may not realize it, but you’re already very experienced with using
methods.

For e.g, to print text to the console, you use the println() or print() methods
To get an integer from the user, you use the nextInt() method.

In all methods, the main method is a method that contains the
statements that are executed when you run your program.

A method can perform some specific task without returning


anything.

 Methods allow us to reuse the code without retyping the code.

In Java, every method must be part of some class which is


different from languages like C, C++, and Python.
DEFINING METHODS

The general format of a method definition is


[access modifier] return-type method-name ([parameter-list]) {

// body of method

Modifier-:
Defines access type of the method i.e. from where it can be accessed in
your application.

Method access modifiers are similar to field access modifiers.

Access modifiers used with methods are: public, private, protected and
default.
DEFINING METHODS (2)
The return type: The data type of the value returned by the method or void if
does not return a value.

Method Name: is any valid identifier

Parameter list: Comma separated list of the input parameters are defined,
preceded with their data type, within the enclosed parenthesis.
 If there are no parameters, you must use empty parentheses ().

The method gets data to process from the parameters during execution .

Exception list: used to handle errors if the method generates exception.

Method body: it is enclosed between braces. The code you need to be


executed to perform your intended operations.
EXAMPLE #1:

Here is the source code of the above defined method called max().

This method takes two parameters X and Y and returns the


maximum between the two.
METHOD SIGNATURE:
Method signature:
It consists of the method name and a parameter list (number
of parameters, type of the parameters and order of the
parameters).

The return type and exceptions are not considered as part of it.

Method Signature: Example #1:

max(int x, int y)
HOW TO NAME A METHOD?
A method name is typically a single word that should be a verb in
lowercase or multi-word that begins with a verb in lowercase followed
by adjective, noun…..

After the first word, first letter of each word should be capitalized. For
example, findSum, computeMax, setX and getX

Generally, a method has a unique name within the class in which it is


defined.

 but sometime a method might have the same name as other method
names within the same class as method overloading is allowed in java.
CALLING METHODS

Methods don't do anything until you call them into action i.e. they will not
be executed until called.

When a method is called, a request is made to perform some action, such as


setting a value, printing statements, doing calculation, connecting to
database, reading a file, etc.

 The code that calls the method contains the name of the method to be
executed and any needed data that the receiving method requires
(argument).

 The required data for a method are specified in the method's parameter list.
HOW METHODS ARE CALLED ?
There are two ways in which a method is called i.e., method returns a
value or returning nothing (no return value).

The process of method calling is simple.


 When a program invokes a method, the program control gets transferred to
the called method.

 This called method then returns control to the caller in two conditions, when :

1. The return statement is executed.

2. It reaches the method ending closing brace.


GENERAL SYNTAX: CALLING METHOD
The general syntax is:

[variable =] objectname.methodname([argument list]);

To call the methods of RightTriangle class defined above:

public static void main(String args[]) {

RightTriangle rt = new RightTriangle();

rt.calculateArea(); //calls the calculateArea method

rt.calculateHypotenuse(); //calls the calculateHypotenuse

method

}
RETURNING VALUES

The real utility of methods comes when they can perform some task such as a
calculation, and then return the value of that calculation to the calling
method,
so the calling method can do something with the value.
To create a method that returns a value, you need two steps:
i. When defining the method, simply indicate the type of the value returned by
the method on the method declaration.
 The return type of a method is simply any of Java’s primitive data types
 Methods that do not return a value use a return type of void instead of data
type.
ii. Use the return statement inside the method to return the value after
computation.
RETURNING VALUES (2)
When you specify a return type other than void in a method declaration,

the body of the method must include a return statement that specifies the
value to be returned.

The return statement has this form:

return value/expression;

The expression must evaluate to a value that’s the same type as the type
listed in the method declaration.

 In other words, if the method returns an int, the expression in the return
statement must evaluate to an int.
PARAMETER PASSING

A parameter is a value that you can pass to a method.

 The method can then use the parameter as if it were a local variable initialized with
the value.

 You can use any data type for a parameter of a method or a constructor.

 This includes primitive data types, such as doubles, floats, and integers, and
reference data types, such as objects and arrays.

Parameters refer to the list of variables in a method declaration.

 Arguments are the actual values that are passed in when the method is invoked.

When you invoke a method, the arguments used must match the declaration's
parameters in type and order.
PARAMETER DECLARATION

A method that accepts parameters must list the parameters in the


method definition.

 The parameters are listed in a parameter list in the parentheses


that follow the method name.

 For each parameter used by the method, you list the parameter
data type followed by the parameter name.

If you need more than one parameter, you separate them with
commas.
PARAMETER DECLARATION….
The syntax for parameter declaration:
return-type method-name (datatype1 parameter1, datatype2 parameter2,
datatype3 parameter3,…) {

//method body

When a method that defines a parameter is called for execution, it expects


passing a value.

The parameter defined in a method could be either a primitive data type


(like int, double, char, etc.) or a reference data types (like object, array,
String, etc).
PARAMETER PASSING WAYS IN JAVA
Java passes everything by value, and not by reference.
 when we say everything, we mean objects, arrays (which are objects in
Java), primitive types (like ints and floats), etc.

 these are all passed by value in Java.

What is the difference between pass by value and pass by reference?


 When passing an argument to a method, Java will create a copy of the value inside
the original variable and pass that to the method as argument – and that is why it is
called pass by value.

The key with pass by value is that the method will not receive the actual
variable that is being passed – but just a copy of the value being stored inside
the variable.
A. PASSING PRIMITIVE TYPES – PASS
BY VALUE
In Java, primitive arguments, such as int, double, float, byte, etc,

are passed into methods by value.

This means that any changes to the values of the parameters exist

only within the scope of the method.

When the method returns, the parameters are gone and any

changes to them are lost.


B. PASSING REFERENCE DATA TYPES – PASS BY VALUE?

Everything is passed by value in Java.

 So, objects are not passed by reference in Java.

 What do we mean here? Objects are passed by reference –


 meaning that a reference/memory address is passed when an object is
assigned to another – but that reference is actually passed by value.

The reference is passed by value because a copy of the reference


value is created and passed into the other object.

So objects are still passed by value in Java, just like everything
B. PASSING REFERENCE DATA TYPES –
PASS BY VALUE?..

Hence, we say all reference data type parameters, such as objects

and arrays, are passed into methods by value.

This means that when the method returns, the passed-in reference

still references the same object as before.

However, the values of the object's fields can be changed in the

method, if they have the proper access level.


CONSTRUCTORS IN JAVA
It can be tedious to initialize all of the variables in a class each time an
instance is created.

Because the requirement for initialization is so common, Java allows


objects to initialize themselves when they are created.

This automatic initialization is performed through the use of a


constructor.

Constructors are used to initialize the object’s state(not create an object)

Like methods, a constructor also contains collection of statements (i.e.


instructions) that are executed at time of Object creation.
NEED OF CONSTRUCTOR

constructors are used to assign values to the class variables at


the time of object creation, either explicitly done by the
programmer or by Java itself (default constructor).
WHEN IS A CONSTRUCTOR CALLED ?
Each time an object is created using new() keyword at least one constructor (it
could be default constructor) is invoked to assign initial values to the data
members of the same class.

A constructor is invoked at the time of object or instance creation.

For Example:
class Box{
// A Constructor
Box() {}
}
// We can create an object of the above class
// using the below statement. This statement calls above constructor.
Box obj = new Box();}
RULES FOR WRITING CONSTRUCTOR
Constructors have no return type, not even void.
 This is because the implicit return type of a class’s constructor is the class type itself.

 It is the constructor’s job to initialize the internal state of an object so that the

code creating an instance will have a fully initialized, usable object

immediately.

A constructor in Java cannot be abstract, final, static and Synchronized.

Access modifiers can be used in constructor declaration to control its

access( i.e . Public, private, protected and default)


TYPES OF CONSTRUCTOR
Broadly, constructors can be divided into three:

i. default constructor,

ii. parameterized constructor and

iii. copy constructor.


 Copy constructor can be seen one type of parameterized constructor.
I. DEFAULT CONSTRUCTORS

If we don’t define a constructor in a class, then compiler


creates default constructor (with no arguments) for the class.

Default constructor, it doesn’t accept any parameters and it


doesn’t do anything, but it does allow your class to be
instantiated.

if we write a constructor with arguments then the compiler does


not create a default constructor.

Default constructor provides the default values to the object like


0, null, etc. depending on the type.
II. PARAMETERIZED CONSTRUCTORS

A constructor that has parameters is known as parameterized

constructor. (create by programmer)

Parameterized constructor is used to provide different values

to the distinct objects.

It initializes the object to the values of the parameter passed

when new keyword is used to create object.


III. COPY CONSTRUCTOR
A copy constructor is a special constructor for creating a

new object as a copy of an existing object.

The first argument of such a constructor is a reference to an object of

the same type as is being constructed, which might be followed by

parameters of any type.

 Once it gets its object argument, creates a copy of it and create new

object.
DIFFERENCE BETWEEN CONSTRUCTOR AND
METHOD IN JAVA

Java Constructor Java Method


 A constructor is used to initialize  A method is used to expose the
the state of an object. behavior of an object.

 A constructor must not have a  A method must have a return type


return type. or void if does not return any
value.
 The constructor is invoked  The method is invoked explicitly.
implicitly.
 The Java compiler provides a  The method is not provided by
default constructor if you don't the compiler in any case.
have any constructor in a class.
 The constructor name must be  The method name may or may
same as the class name. not be same as the class name.
 Constructor is called only once at  Method(s) can be called any
the time of Object creation
numbers of time.
THIS KEYWORD
Sometimes a method will need to refer to the object that invoked it.

To allow this, Java defines the this keyword.

this is a keyword in Java which is used as a reference to the object of


the current class, with in an instance, method or a constructor.

i.e. Using this you can refer the members of a class such as
constructors, variables and methods as shown in fig below:
ACCESSING MEMBERS
To access data members and methods of classes using objects, we use the dot(.)
operator.

This is the only way to access members of class since Java does not support pointers.

 This has the general format like:


objectname.field;

objectname.method();

Example: accessing data members and methods

System.out.println(b1.width);
System.out.println(b1.height);
b1.calcArea();
System.out.println(b1.area);
STATIC MEMBERS
In classes, it is possible to create a member (method or field) that can

be used by itself, without reference to a specific instance of a class.

 Such members are called static members.

To create such a member, precede its declaration with the keyword

static.

When a member is declared static, it can be accessed before any

objects of its class are created, and without reference to any object.
STATIC MEMBERS(2)
The most common example of a static member is main( ).

main( ) is declared as static because it must be called before any objects


exist.

Instance variables declared as static are, essentially, like global variables.

When objects of its class are declared, no copy of a static variable is


made.

Instead, all instances of the class share the same static variable.

You can declare both methods and variables to be static.


INSTANCE VARIABLE HIDING
it is illegal in Java to declare two local variables with the same
name inside the same or enclosing scopes.

Interestingly, you can have local variables, including formal


parameters to methods, which overlap with the names of the
class’ instance variables.

However, when a local variable has the same name as an


instance variable, the local variable hides the instance variable.
JAVA GARBAGE COLLECTION
Since objects are dynamically allocated by using the new
operator, you might be wondering how such objects are destroyed
and their memory released for later reallocation.

In some languages, such C/C++,


programmer is responsible for both creation and destruction of
objects.

Usually programmer neglects destruction of useless objects.

Dynamically allocated objects must be manually released by use of a


delete operator.
JAVA GARBAGE COLLECTION (3)
In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory

automatically.

 In other words, it is a way to destroy the unused objects automatically.

So, java provides better memory management.

Advantage of Garbage Collection


 It makes java memory efficient because garbage collector removes the unreferenced objects

from heap memory.

 It is automatically done by the garbage collector (a part of JVM) so we don't need to make

extra efforts.
HOW CAN AN OBJECT BE
UNREFERENCED?
There are many ways:
 By nulling the reference
Employee e=new Employee();
e=null;

 By assigning a reference to another


Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection

 By anonymous object etc.


new Employee();
INNER CLASSES AND ANONYMOUS INNER
CLASSES
Questions?
 What is nested classes

 What is Inner classes?

 Why do we need Inner Classes?

 What is Anonymous Classes

 When we uses Anonymous Classes?


NESTED CLASSES

In Java, just like methods, variables of a class too can have another class as its member. i.e.
Writing a class within another is allowed in Java.

The class written within is called the nested class, and the class that holds the inner class is
called the outer class.

The scope of a nested class is bounded by the scope of its enclosing class.
 For example, if class B is defined within class A, then B is known to A, but not outside of A.

A nested class has access to the members, including private members, of the class in
which it is nested.

However, the enclosing class does not have access to the members of the nested class.
General Syntax of Nested Classes

Following is the syntax to write a nested class.


class Outer_Demo {
class Inner_Demo {
}
}
 Here, the class Outer_Demo is the outer class and the
class Inner_Demo is the nested class.
TYPES OF NESTED CLASSES
Nested classes are divided into two types −

Note:
 Non-static nested classes − these are the non-static members of a class.

 Static nested classes − these are the static members of a class.


A. INNER CLASSES (NON-STATIC
NESTED CLASSES)
Inner classes are a security mechanism in Java.

We know a class cannot be associated with the access modifier private,

but if we have the class as a member of other class, then the inner class
can be made private.

this is used to access the private members of a class.

Inner classes are of three types depending on how and where you
define them. They are −
i) Inner Class ii) Method-local Inner Class iii) Anonymous Inner Class
I. INNER CLASS
The most important type of nested class is the inner class.

An inner class is a non-static nested class.

It has access to all of the variables and methods of its outer class and may
refer to them directly in the same way that other non-static members of
the outer class do.

Thus, an inner class is fully within the scope of its enclosing class.

Creating an inner class is quite simple. You just need to write a class
within a class.

 Unlike a class, an inner class can be private and once you declare an
inner class private, it cannot be accessed from an object outside the class.
DECLARING INNER CLASSES

The basic structure for creating an inner class is as follows:

class outerClassName
{
//body of outer class
[private|protected|public] class innerClassName
{
// body of inner class
}
}
EXAMPLE #1: INNER CLASS
class Outer_Demo { public class My_class {
int num; public static void main(String args[]) {
// inner class
// Instantiating the outer class
private class Inner_Demo {
Outer_Demo outer = new Outer_Demo();
public void print() {
System.out.println("This is an inner class"); // Accessing the display_Inner() method.
} outer.display_Inner();
} }
// Accessing the inner class from the method within
}
void display_Inner() {
Inner_Demo inner = new Inner_Demo();
inner.print(); Output: This is an inner
}
class.
}
HOW INNER CLASS IS WORKS?
The outer class first has to create instance of the inner class before
using it.

Just like it is necessary to create instance of any other classes, the


same is true for inner classes.

Form example, you can observe that


 Outer_Demo is the outer class,

 Inner_Demo is the inner class,

 display_Inner() is the method inside which we are instantiating the inner class, and
this method is invoked from the main method.
II. METHOD-LOCAL INNER CLASS
In Java, we can write a class within a method and this will be a
local type.

Like local variables, the scope of the inner class is restricted


within the method.

A method-local inner class can be instantiated only within the


method where the inner class is defined.

The next example shows how to use a method-local inner class.


EXAMPLE: METHOD-LOCAL INNER
CLASS
class Outerclass { // Accessing the inner class
MethodInner_Demo inner = new
// instance method of the outer MethodInner_Demo();
class
inner.print();
void my_Method() { }
}
int num = 23;
public class LocalInnerClass {
// method-local inner class public static void main(String[]
args) {
class MethodInner_Demo {
// TODO code application logic
public void print() { here
Outerclass outer = new Outerclass();
System.out.println("This is outer.my_Method();
method inner class "+num);
}
} }
Output: This is method inner class 23
} // end of inner class
Anonymous Inner Classes

An inner class declared without a class name is known as an

anonymous inner class.

In case of anonymous inner classes, we declare and instantiate

them at the same time.

 Generally, they are used whenever you need to override the

method of a class or an interface.


GENERAL SYNTAX OF ANONYMOUS CLASS

The syntax of an anonymous inner class is as follows −


new ClassOrInterface() {
class-body
}
};

The next example, shows how to override the method of a class


using anonymous inner class.

You might also like