0% found this document useful (0 votes)
2 views22 pages

OOPS Using JAVA Unit-2 Notes

This document provides comprehensive notes on Object Oriented Programming (OOP) using Java, focusing on classes, objects, methods, constructors, method overloading, access specifiers, and static members. It explains the fundamental concepts of class definitions, object instantiation, and the use of constructors for initialization. Additionally, it covers access control mechanisms and the significance of static members in Java programming.

Uploaded by

recurredyou
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views22 pages

OOPS Using JAVA Unit-2 Notes

This document provides comprehensive notes on Object Oriented Programming (OOP) using Java, focusing on classes, objects, methods, constructors, method overloading, access specifiers, and static members. It explains the fundamental concepts of class definitions, object instantiation, and the use of constructors for initialization. Additionally, it covers access control mechanisms and the significance of static members in Java programming.

Uploaded by

recurredyou
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Object Oriented Programming (OOP) Using

JAVA

Unit-2 Notes
Dr. Paramesh S.P
Assistant Professor
Dept. of CS & E
School of Engineering
Central University of Karnataka
Unit-2 Contents
• Introduction to Classes, Objects and Methods
• Class Fundamentals, Defining a Class
• Declaring Objects
• Introducing Methods
• Example programs
• Contructors, examples
• Method Overloading, examples
• Access Control (Access Specifiers in Java), examples
• Understanding Static Members, examples
Classes, Methods and Objects
Classes
• Java is a true object oriented language and therefore underlying structure of all java
programs is classes.

• Anything we wish to represent in java program must be encapsulated in a class that


defines the state and behaviour of the basic program components known as objects.

• Classes provide a convenient method for packing together a group of logically


related data items and functions that work on them.

• In java, data items are called fields/variables and the functions are called methods.

• Class behaves like a basic data type such as int, float etc.. Once the class is defined,
this new datatype can be used to create objects of that type. Thus, a class is a
template for an object and an object is an instance of the class.
Classes, Methods and objects
Defining a Class/ General form of a class
• A simplified general form/Syntax of a class definition in Java is shown below:
Class ClassName {
[variable declaration];
[methods declaration]
}
Here, everything inside the square bracket is optional.
• Detailed form of class definition is show below
class ClassName
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) { // body of method }
type methodname2(parameter-list) { // body of method }
// ...
type methodnameN(parameter-list) { // body of method }
}
Classes, Methods and objects
• In Java, a class is declared by using the class keyword.
• ClassName is a valid Java Identifier but convention is that always the first letter of the
class should start with a Uppercase letter.
• classes usually consist of two things: instance variables and methods. These two are
called the members of the class.

Instance Variable Declaration


• The data/fields/variables are encapsulated within the class. These variables are called
instance variables because each instance of the class (that is, each object of the class)
contains its own copy of these variables.
• Instance variables are defined exactly the same way as that of local variables.
• Syntax for defining a instance variables:
type var1[=value], var2[=value], var3[=value],…..,varN[=value];
Here, value is optional and comma is used to separate more than one variables.
Ex: int length, width;
Classes, Methods and objects
Instance method Declaration
• Classes without methods has no life. We must therefore add methods to manipulate the data.
• The general form/Syntax of method declaration is given below.

type method-name(parameter-list)
{
// body of method
}
Here, type specifies the type of data returned by the method. This can be any valid type (ex: int, float, void etc.) including class
types that we create. If the method does not return a value, its return type must be void.
The name of the method is specified by name. This can be any legal identifier.
The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that
receive the value of the arguments passed to the method when it is called.
If the method has no parameters, then the parameter list will be empty.

Ex: void getData(int x, int y)


{
length=x;
Width=y;
}
Classes, Methods and Objects
Below examples shows a simple class containing instance variables and methods in it.
Example 1:

Example 2:
Classes, Methods and Objects
Declaring Objects in JAVA
When we create a class, we are creating a new data type. we can use this type to declare
objects of that type.
In Java, obtaining objects of a class is a two-step process which involves

1. Declaration of variable of class type : This variable does not define an object.
Instead, it is simply a variable that can refer to an object.
Ex: Rectangle obj; // obj is reference variable of class Rectangle

2. Instantiate an object using new operator: The new operator dynamically allocates
(that is, allocates at run time) memory for an object and returns a reference to it. This
step acquire an actual, physical copy of the object and assign it to that variable.
Ex: obj= new Rectangle();
Classes, Methods and Objects
We can combine both these steps into a single statement as below to create an object of
Rectangle class i.e,
Rectangle obj=new Rectangle();
Similarly we can create an object of Box class using the below statement.
Box obj1=new Box(); // here obj1 is the object of type Box.
In general, the following syntax is used to create objects of a class.
Syntax: className objectName=new className();
Here, objectName is a valid Java identifier and usually starts with lowercase letter as per the Java
coding conventions.
Ex: Box obj1=new Box();
Note:
We can create any number of objects of the same class type.
Each objects will be having its own copy of instance variables and methods.
Changes made to the instance variable by one object have no effect on the variables of another
object.
Once we create an object of a class, the members of the class can be accessed by using .(dot)
operator.
Classes, Methods and Objects
Write a Java Program to demonstrate
• creation and usage of a class (containing instance variables and methods in it)
• creating an object of that class and accessing the members of the class through the object.
Classes, Methods and Objects
One more example to demonstrate the usage of classes, creation of objects and accessing the members of the class through the
object.
Constructors
Constructors
• It can be tedious to initialize all of the variables in a class each time an instance/object is created.
• Java allows objects to initialize themselves when they are created. This automatic initialization is
performed through the use of a constructor.
• A constructor is a special method having the same name as that of the class.
• A constructor is called during the object creation and it initializes all the instance variables.
• The constructor is automatically called when the object is created, before the new operator
completes.
• constructors doesn’t have any return type, not even void. This is because the implicit return type
of a constructor is the class type itself.
• So, 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.
• If the constructor is not explicitly defined in the class, a default constructor is invoked/called during
object creation which will initializes all the instance variables to their default values. Following are
the default values of various types of variables.
int – 0
float – 0.0
char- null
boolean- false
Constructors
Program to demonstrate the use of constructor.

In this program, class Box


contains a constructor
called Box()
[note that constructor is
having the same name as
that of the class] and this
constructor initializes
values of the instance
variables.

The constructor B() is called


when the object is created,
before the new operator
completes.
i.e, Box obj=new Box()
// Here, Box() is a
constructor.
Constructors
Parameterized Constructors
We can also define a parameterized constructor to initialize the values of the instance variables. Following Program demonstrate
the use of Parameterized constructors. (This program is also an example for constructor overloading)
Method overloading in JAVA
Method Overloading
• In Java, it is possible to define two or more methods within the same class that share the same name,
as long as their parameter declarations are different. When this is the case, the methods are said to be
overloaded and the process is referred to as method overloading.

• Method overloading is a type of polymorphism in Java wherein a class can have two or more methods
with the same name as long as the parameters are different.

• When an overloaded method is invoked, Java uses the type and/or number of arguments/parameters
as its guide to determine which version of the overloaded method to actually call. Thus, overloaded
methods must differ in the type and/or number of their parameters.

• While overloaded methods may have different return types, the return type alone is insufficient to
distinguish two versions of a method. When Java encounters a call to an overloaded method, it simply
executes the version of the method whose parameters match the arguments used in the call.

• Method overloading is also called compile time polymorphism as the version of the overloaded method
to be executed is decided during the compile time of program execution.
Method Overloading
Program to demonstrate the method overloading.

NOTE:
In the example program, we can
observe that the method named
test is overloaded 4 times with
different parameters.
The program executes the
version of the method whose
parameters match the arguments
used in the call.
Access Specifiers/Modifiers in JAVA
Access Specifiers
• Java Supports a mechanism by which we can precisely control the access to the various members (i.e, instance variables
and instance methods) of the class.
• Java access specifiers are public, private and protected. If no access specifier is mentioned then it is default access level.
• All the access specifiers are keywords in Java.
• The syntax for defining the access specifier to the members of the class is given below.
For variables:
<access specifier name> <datatype> var-name;
ex: private int a;
public int b;

For methods:
<access specifier name> <datatype> method-name() {
// body of the method
};
Ex: public void show()
{
System.out.println(“Hello”);
}
Access Specifiers/Modifiers in JAVA
The access specifiers are described below.
public:
• Any variable or method declared with public has the widest possible visibility and accessible everywhere.
• Members (variable or methods) declared with public can be accessed by all classes in the same package and other packages.
(Note: A package is a group related classes).
• ex:
public int number;
public void sum() {……}
Here, the variable number and the method sum() can be accessed by all the classes in the same package as well by all the classes
in different package.

private:
• private members enjoy the highest degree of protection.
• private members are accessible only with their own class and are restricted outside the class.
• They cannot be inherited by subclasses and therefore not available in subclasses.
• ex:
class A
{ private int x;
private void display(){…..};
}
Here, both the variable ‘x’ and the method display are available only in the class A and not available out side of class A.
Access Specifiers/Modifiers in JAVA
protected:
• The visibility level of “protected” field lies in between the public access and friendly access.
• The members (i.e., variables and methods) declared with protected modifier are available to all classes within the
same package and also to the subclasses defined in the other packages.
ex:
protected int x;
protected void display() {…….}
Here, the variable ‘x’ and the method display() are accessible to all the classes in the same package and subclasses
of other packages.

default or friendly access:


• When a member of the class is not defined with any of the access modifier, then it is a default access.
• The members of the class without any access specifier (i.e., default access) are available to all the classes in the
same package but not in other packages.
ex:
int a;
void display() {…}
Here, both variable ‘a’ and display() method are not defined with any of the access specifier and hence it is a default
access and are available to all the classes within the same package.
Access Specifiers/Modifiers in JAVA
Program to Demonstrate various access specifiers. Note: In this program,
• The variables a and b can
be accessible outside class
A as they are declared
with default and public
access specifier
respectively.

• The methods show() and


display() are accessible
outside class A as they are
declared with default and
public access specifiers
respectively.

• The variable ‘c’ is declared


with private access
specifier and hence
accessible only within class
A and not outside of A.
Hence, this program
results in compilation
error.
Understanding static keyword in JAVA
Static Members.
• A class in Java basically contains two sections. One declares the variables and the other declares the methods. These variables and
methods are called instance variables and instance methods. This is because every time the class is instantiated, a new copy of object
is created.
• Instance variables and methods are also called as non static variables and non static methods respectively.
• We can create any number of objects of the same class and each object will be having its own copy of members.
• Members of the classes are accessed using the objects with dot operator.
• Incase, if we want to define a member that is common to all the objects of the same class and to be accessed without creating an
object of the class then we have to define that member as static as below.
static int count;
static int max(int x, int y) {…..}
The members that are declared static as shown above are called static members.
Points to remember about static members:
1. The static members belongs to the class as a whole rather than the objects created from the class.
2. The static variables and static methods are often referred to as class variables and class methods in order to distinguish them from
their counterparts instance variables and instance methods.
3. Static variables are used when we want to have a variable common to all the instances (objects) of the class. Every object will share
the copy of the static variable i.e., the value of static variable persist among all the objects of the class.
4. Static variables and methods can be accessed without creating/instantiating an object of the class.
5. Static members can be accessed using the classname with .(dot) operator as follows.
classname.variable-name; //ex: Box.length ; here, Box is a classname and length is static variable
classname.method-name(); // ex: Box.area(); here, Box is a classname and area() is a static method.
Understanding static keyword in JAVA
Program to define and use the static members
Note: In this program,
• static method display() can be
accessed directly using the
classname and . operator. i.e,
Stat_Demo.display();

• static variable 'a' can be


accessed directly using
classname and .operator
i.e, Stat_Demo.a();

• static variable ‘b’ can be


accessed directly using
classname and .operator
i.e, Stat_Demo.b();

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy