Nothing Special   »   [go: up one dir, main page]

Chapter 4 OOP PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

OOP in Java By: Naol G.

2021

Chapter-4

Classes and Object

Introduction

Java is a true object-oriented language and therefore the underlying structure of all Java
programs is classes. A class is a template or prototype that defines a type of object. Everything
we wish to represent in a Java program must be encapsulated in class. Class defines the state and
behavior of the basic programming components known as objects. A class defines the skeleton of
an object. Classes create objects and objects use methods to communicate between them. This is
all about object-oriented programming.

A class is a blueprint that defines the states and the behaviors common to all objects of a certain
kind. An object is a software bundle that has State and Behaviour. An Object's state is stored in
variables called fields. An Object's behaviour is defined by its methods.

Example 1: Dogs (States: name, color, breed, and “is hungry?” and Behaviors: bark, run, and
wag tail). Example 2: Cars (States: color, model, speed, direction and Behaviors: accelerate,
turn, change-gears)

General form of class  class indicates that a class


named clsName is being declared. It
must follow the java naming
conventions for identifiers.

 Instance variables named varName1


through varNameN are normal variable
declaration syntax. Each variable must
be assigned a type shown as type1
through typeN and may be initialized to
a value shown as valueN.

 Constructors always have the same


name as the class. They do not have
return values. cparam1 through
cparamN are optional parameter lists.

 Methods named mthName1 through


mthNameN can be included. The return
type of the methods are rtype1 through
rTypeN and mParamN aew an optional
parameter lists.
OOP in Java By: Naol G. 2021

Adding variables to class

Data is encapsulated in a class by placing data fields inside the body of the class definition.
These variables are called instance variables (member variables) because they are created when
an object of the class is instantiated. These variables are created exactly the same way as we
declare local variables.

Example:

Adding Methods to class

A class with only data fields (and without methods that operate on that data) has no life. Methods
are declared inside the body of the class but immediately after the declaration of the instance
variables. The general form of a method declaration is:

type methodname (parameter-list)


{
method-body;
}

Method declaration has four parts:

 The name of the method (methodname).


 The type of the value the method returns (type).
 A list of parameters (parameter-list).
 The body of the method

The type specifies the type value the method would return. This could be a simple data type such
as int as well as any class type. It could be void type, if the method does not return any value.
The methodname is a valid identifier. The parameter-list is always enclosed in parenthesis and
contains variable names and types of all the values we want to give to the method as input.
OOP in Java By: Naol G. 2021

Example:

Creating Objects

An object in Java is essentially a block of memory that contains space to store all the instance
variables. Creating an object also known as instantiating an object. Objects in Java are created
using the new operator. The new operator creates an object of the specified class and returns a
reference to that object.

Syntax for object creation:

classname objectname; //declares a variable to hold the object reference

objectname = new classname( ); // Assigns the object reference to the variable

Example:
OOP in Java By: Naol G. 2021

Accessing class Members

To access members (fields and the methods) of an object use the dot (.) operator together with
the reference to an object. The general syntax is as follows:

objectname.variablename;

objectname.methodname(parameter-list);

Example:

Assigning Object Reference Variables

When you assign one object reference variable to another object reference variable, you are not
creating a copy of the object, you are only making a copy of the reference.
OOP in Java By: Naol G. 2021

Example:

Constructors

It can be tedious to initialize all of the variables in a class each time an instance is created. Even
when you add convenience functions like giveName(). It is possible to initialize objects they are
created by using the dot (.) operator and with the help of methods. But it would be simpler and
more concise to initialize an object when it is first created. Java supports a special type of
method, called a constructor, that enables an object to initialize itself when it is created.

Constructors are special methods that are used to construct an instance of a class. A constructor
initializes an object immediately upon creation. But object creation only doesn‟t call constructor
rather it will be called when the object is instantiated. Call the constructor(s) preceding it with
the new keyword.
OOP in Java By: Naol G. 2021

Rules with Constructors

 Class name and constructor name should be the same. That is, it has the same name as the
class in which it resides and is syntactically similar to a method.
 Constructors have no return type (not even void), this is because they return the instance
of the class itself.
 Constructors should be public.
 Constructors cannot be inherited.
 They can be overloaded. Many constructors with the same name can be defined.

Types of Constructors

 Default constructor: is the type of constructor with out any argument.


 Parameterized Constructor: is a constructor with one or more argument.

When an instance of an object is created then the instance will call the constructor. It will be the
default constructor which will be called, if there are no any parameterized constructor. But if
there is any parameterized constructor, then it will be the parameterized constructor with the
specified parameter(s) which will be called.

Default Constructor

When you do not write a constructor in a class, it implicitly has a constructor with no arguments
and an empty body.

But we can also have a default constructor with no parameter(s) as follows:


OOP in Java By: Naol G. 2021

Parameterized Constructors

We can also have the constructor which take one or more argument.

Example:

this Keyword

Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines
the this keyword. Instance can refer to itself with the keyword this.

Example: Similar to the above code, but to show how „this‟ keyword used!
OOP in Java By: Naol G. 2021

Passing arguments by-value, by-reference

There are two ways that a computer language can pass an argument to a subroutine.(passing by
value and passing by reference).

 Passing by-value: - This method copies the value of an argument into the formal
parameter of the subroutine. Therefore, changes made to the parameter of the subroutine
have no effect on the argument. It‟s to pass primitive data types values.
 Passing by-reference: - In this method, a reference to an argument (not the value of the
argument) is passed to the parameter. To pass objects, changes made to the parameter
will affect the argument used to call the subroutine.

Example-1: Passing by-value: change will no happen to instance variables ‘name’ and ‘idno’!
OOP in Java By: Naol G. 2021

Example-1: Passing by-reference: change will happen to instance variables ‘name’ and ‘idno’!

Access modifiers in Java

Access modifiers in Java are used to specify the access levels for classes, variable methods, and
constructor. It helps in updating the value of a variable. They are also known as visibility
modifier. There are four access modifiers keywords in Java :

 Default Access Modifier


 Public Access Modifier
 Protected Access Modifier
 Private Access Modifier

Accessibility of java modifiers

 To make visible to the package: we use default, which has no modifiers name.
 To make visible to the class only: we use private
 To make visible to the world: we use public
 To make visible to the package and all subclasses: we use protected
OOP in Java By: Naol G. 2021

Example: Assume we have two different packages „student‟ and „teacher‟:

Now assume class TestModifiers found in teacher package, and class Student
found in student package:

This is Student class in student package, which contains protected method called giveNameId().

And TestModifiers class found in teacher package that need to access method inside
Student class. To do that, TestModifiers must be child of Student class (via „extends‟
OOP in Java By: Naol G. 2021

keyword). Protected members from different package can only be accessed through child
class.

Here is the code to do that:

Static Members

Static members of a class a class are created using a key word static , and those members can be
accessed without reference to any object of the class. Methods declared as static have several
restrictions:

 They can only call other static methods.


 They must only access static data.
 They cannot refer to this or super in any way. (The keyword super relates to inheritance
and is described in the next chapter.)

Note: It is illegal to refer to any instance variables inside of a static method.

As soon as the UseStatic class is loaded, all of the static statements are run. Outside of the class
in which they are defined, static methods and variables can be used independently of any object.
To do so, you need only specify the name of their class followed by the dot operator.

General syntax:

classname.variable;

classname.method( );
OOP in Java By: Naol G. 2021

Example: Accesing class members through class itself, without instantiating an object.

Garbage Collection

Java it handles de-allocation of memory taken by objects automatically. The technique that
accomplishes this is called garbage collection. When no references to an object exist, object is
assumed to be no longer needed, and the memory occupied by the object can be reclaimed.

What will happen to the memory pointed by both st1 and st2 if both points to null? st1=st2=null;

You might also like