Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

OOP in Java Unit4

Java programming note. Unit 4

Uploaded by

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

OOP in Java Unit4

Java programming note. Unit 4

Uploaded by

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

BY: MANOJ SAPKOTA, NEPAL POLYTECHNIC INSTITUTE

UNIT 4: Classes and Objects

Class: Class is a user-defined data type that holds various variables and
methods under one construct. It is regarded as a template or blueprint of the
objects. It is a collection of the objects. Example of a class could be a template
that represents a collection of books in a library, or a number of students at a
college, or number of employees in an organization.

Class declaration/definition: A class is defined by using the keyword ‘class’


followed by the name of the class. The body of the class is defined inside the
curly brackets.
Syntax:
class Class_Name
{
// variables (fields)
// methods
}

Example:
class Student
{
String name; // variable (field)
int roll; // variable (field)
void study( ) { //method

}
}

Class variables:
• These are also known as fields.
• These are used to store the data.
• They define the properties of the objects.

Class methods:
• They are used to perform certain operations.
• They are used to manipulate the data stored in variables (fields).
• They define the behaviors of the objects.

1
BY: MANOJ SAPKOTA, NEPAL POLYTECHNIC INSTITUTE

Objects: The objects are the real-world entities. The objects are the instances of
a class. Example of object could be any entity such as particular book, a student,
an employee, etc. The fields and methods defined inside the class are accessed
by creating an instance (object) of the class.

Declaring/Creating objects: The objects are created from classes. They are
created(declared) as follows:
Syntax: Class-name object-name = new Class-name( );
Example: Student s = new Student( );
Where, ‘Student’ is a class-name and ‘s’ is an object.

Accessing members of class: The members of the class can be accessed using
the dot (.) operator with the object.
Syntax: objectName.fieldName; //accessing variable
objectName.methodName( ); //accessing method
Example: s.roll; //accessing variable
s.name; //accessing variable
s.study( ); //accessing method
Here, ‘s’ is the name of the object. It is accessing the fields and methods
by using dot(.) operator.

Example Program:

2
BY: MANOJ SAPKOTA, NEPAL POLYTECHNIC INSTITUTE

Output- Name: Kiran


Roll: 15

Method parameters: When a method is called, information can be passed to it


in the form which are known as parameters. These parameters act as variables
inside the method.

The parameters are specified inside the parentheses ‘( )’ after the method name.
There can be multiple parameters which are separated by comma.

Example:
void sum (int a, int b) //method definition, where ‘a’ and ‘b’ are parameters
{
// code
}
When the above method ‘sum’ is called, it can receive information in the form of
parameters ‘a’ and ‘b’.

Access control: It is a mechanism used to control the accessibility of specific


codes or data within a Java program. It is used to determine what parts of a
program can be accessed and manipulated by other which parts of the program.
It is used to restrict or allow access to parts of the program, such as classes,
methods and variables.

Access control mechanism in Java promotes code encapsulation and information


hiding. It helps to maintain security and reduce errors in the program. The
access control can be implemented by using the access modifiers.

Access modifiers/specifiers: These are the keywords that are used to control
the access (visibility) of certain parts of the program such as classes, methods
and variables. There are four access modifiers in Java. They are:
1. Private
2. Default
3. Protected
4. Public

1. Private: This is the modifier that makes the members of the class (methods or
variables) private and doesn’t allow them to be accessible from outside the class.
These members can only be accessed from within the class. The ‘private’ keyword
is used for this purpose.

3
BY: MANOJ SAPKOTA, NEPAL POLYTECHNIC INSTITUTE

Example:
class Student
{
private String name; //private variable
private int roll; //private variable
}

2. Default: This is the modifier that makes the classes or its members accessible
within the same package but not from outside the package. If the classes,
methods or variables are not specified with any modifiers, then by default, they
will be considered under default modifiers.

Example:
class Student
{
String name; // default variable
int roll; // default variable
}

3. Protected: This is the modifier that makes the members of the class protected
and doesn’t allow them to be accessible from outside the same package, except
from the derived classes. That means, these members can only be accessed from
within the same package and from the derived classes of other packages. The
‘protected’ keyword is used for this purpose.

Example:
class Student {
protected String name; // protected variable
protected int roll; // protected variable
}

4. Public: This is the modifier that makes the class or its members public and
allow them to be accessible from anywhere in the program. The ‘public’ keyword
is used for this purpose.

Example:
class Student {
public String name; // public variable
public int roll; // public variable
}

4
BY: MANOJ SAPKOTA, NEPAL POLYTECHNIC INSTITUTE

Summary Table:

Table: Various Access Modifiers

Static variable: Some of the characteristics of the static variable are as follows:
• It is a variable that belongs to the class and not to the object. So, it is also
known as class variable.
• It has a single copy and it is shared by all the objects of the class.
• It is initialized only once at the start of the execution.
• It doesn’t need any object and can be accessed directly by the class name.
• It can be accessed by both the static and non-static methods.

An example program that demonstrates static variable is shown below.


Example Program:

Output- Count Value: 12

5
BY: MANOJ SAPKOTA, NEPAL POLYTECHNIC INSTITUTE

Static method: Some of the characteristics of static method are as follows:


• It is a method that belongs to the class and not to the object. So, it is also
known as class method.
• It can access only static data. It cannot access non-static data.
• It doesn’t need any object and can be accessed directly by the class name.
• ‘this’ and ‘super’ keywords cannot be used directly in static method.

An example program that demonstrates static method is shown below.


Example Program:

Output- Value of a: 5

Another example program that demonstrates the static method which is within
the same class is shown below:

6
BY: MANOJ SAPKOTA, NEPAL POLYTECHNIC INSTITUTE

Output- Value of a: 2

Static block: It is a block of statement inside a class that is used for initializing
the static variables. This block will be executed only once when the class is first
loaded into the java virtual machine. A class can have multiple static blocks,
which will execute in the same sequence in which they have been written in a
program.

An example that demonstrates the static block is shown below.


Example Program:

Output: Static block initialized.


Value of x: 10
Value of x: 20

Method Overloading: It is a feature in java that allows us to have more than


one function in a class having the same name but with different parameter list.
The parameter list should be of different types, or they should be different in
number.

Few examples of declaration of method overloading are shown below:


void sum(int a, int b);
void sum(int a, int b, int c);
void sum(int a, float b);

The above methods have the same function name but their parameter list are
different. So, the situation above is called as method overloading.

7
BY: MANOJ SAPKOTA, NEPAL POLYTECHNIC INSTITUTE

An example program that illustrates method overloading is shown below.

Example Program:

Output: Sum= 2
Sum= 7

Types of method calls: Depending on how the arguments are passed to a


method, there are two type of method calls. They are:
1. Call by value
2. Call by reference

1. Call by value: When the copy of the actual parameter’s value is passed to the
method during its call, it is known as call by value. Any changes made to the
parameters inside the called method have no effect on actual parameter outside
the method.

It can be illustrated by the following program example.

8
BY: MANOJ SAPKOTA, NEPAL POLYTECHNIC INSTITUTE

Example program:

Output: Before method call, value of num= 5


After method call, value of num= 5

2. Call by reference: When the address (reference) of the parameter is passed


to the method during its call, it is known as call by reference. In Java, this type
of call is only possible for objects and not for the primitive data types. So, when
an object is passed to a method, the address (reference) of that object is passed
and not the copy of the object itself. Any changes made to the object inside the
called method will be reflected in the original object outside the method.

It can be illustrated by the following program example.


Example program:

Output: Before method call, value of num= 5


After method call, value of num= 20

9
BY: MANOJ SAPKOTA, NEPAL POLYTECHNIC INSTITUTE

Setters and Getters: These are the methods that are used to protect the data
and make the code more flexible and secure. These methods support the concept
of encapsulation and data hiding.

Setters: These are the methods that are used to set the value of a private variable
(field) of a class. They start with word ‘get’ followed by the variable name, with
the first letter in upper case.

Getters: These are the methods that are used to retrieve (get) the value of a
private variable (field) of a class. It starts with word ‘set’ followed by the variable
name, with the first letter in upper case.

Both the setters and getters are kept public. The setter and getter methods can
be illustrated by the following program example.

Example program:

Output: Kiran

Constructor: A constructor is a special type of method that is called


automatically when an object of the class is created. It has the same name as
that of the class and does not have any return type.

Use of constructor: Constructor is used to initialize the objects. That means, it is


used to set the initial values for the attributes (variables) of the objects.

10
BY: MANOJ SAPKOTA, NEPAL POLYTECHNIC INSTITUTE

Syntax:
class Class_Name
{
Class_Name ( ) //Constructor
{

}
}

An example of the constructor is shown in program below.

Example Program:

Output: Constructor called

Types of constructors: Constructor can be divided into three different types.


1. No-Arg constructor or default constructor
2. Parameterized constructor
3. Copy constructor

1. No-Arg constructor: It is the type of constructor that does not accept any
parameters. It is a type of constructor that is automatically provided by Java if
we don’t define any constructor in the class. So, it is also known as default
constructor. But Java won’t create this constructor if we explicitly implement it.
This type of constructor can be used if we want to initialize the variables of the
object using default values.

An example of the No-Arg (default) constructor is shown in program below.

11
BY: MANOJ SAPKOTA, NEPAL POLYTECHNIC INSTITUTE

Output- Semester: 1

2. Parameterized constructor: It is the type of constructor that accepts


parameters. The parameters are used to initialize the fields (variables) of the
object. So, the parameterized constructor is used if we want to initialize the
variables of the object with our own values.

12
BY: MANOJ SAPKOTA, NEPAL POLYTECHNIC INSTITUTE

Output- Roll: 12

3. Copy constructor: It is the type of constructor that accepts another object as


a parameter. This type of constructor is used to initialize the newly created object
from an existing object. The data available from the previous object is copied to
the newly created object.

An example of the copy constructor is shown in program below.

Example Program:

Output- College Name: NPI


College Name: NPI

this keyword: In java, ‘this’ keyword is a reference variable that is used to refer
to the current object inside a method or a constructor. It is basically used to
differentiate between the instance variables (variables of the object) and
parameters (local variables) if they have the same name.

13
BY: MANOJ SAPKOTA, NEPAL POLYTECHNIC INSTITUTE

It is illustrated in the following program example.

Example Program:

final modifier: The ‘final’ modifier is used to denote constants. It can be used
with variables, methods and classes. Once any entity (variable, method or class)
is declared final, it can be assigned only once. That means,
• the final variable cannot be reinitialized with another value.
Example:
final int age =20;
age=22; //gives compiler error

• the final method cannot be overridden


Example:
class Person{
final void getInfo( ) {
System.out.println("Person class");
}
}
class Student extends Person {
void getInfo( ) { // throws compilation error
System.out.println("Student class");
}
}

14
BY: MANOJ SAPKOTA, NEPAL POLYTECHNIC INSTITUTE

• the final class cannot be extended.


Example:
final class Person {
void getInfo( ) {
System.out.println("Person class");
}
}
class Student extends Person { //throws compilation error
void getInfo(){
System.out.println("Student class");
}
}

Nested classes: A class within another class is known as nested class.


Syntax:
class Outer_class {
……
class Nested_class {
………
}
}

There are two types of nested classes in Java. They are:


1. Static nested class
2. Non-static nested class (inner class)

1. Static nested class: It is a static class defined inside another class. It has
access to only the static members of the outer class. To create an object of such
class, it is not mandatory to create the object of the outer class and can be
created directly using the outer class name.

Syntax to create the object of the static nested class:


OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass( );

It can be illustrated by the following program example.

15
BY: MANOJ SAPKOTA, NEPAL POLYTECHNIC INSTITUTE

Output- Age: 20

2. Non-static nested class: It is also known as inner class. It is a class within


another class. It has access to both the static and non-static members of the
outer class. To create an object of such inner class, the object of the outer class
has to be created at first.
Syntax to create the object of inner class:
OuterClass.InnerCLass innerObject = outerObject.new InnerClass( );

It can be illustrated by the following program example.

Output- Id: 5

16

You might also like