Oopt Java Unit-2 Material
Oopt Java Unit-2 Material
1. Introduction to Classes
Java is a pure object-oriented language. The class is the basis of an object-oriented
programming language. The class acts as a blueprint from which objects can be created. The
object is an instance of class. We can create any number of objects from a class. The class is the
type of the objects. There are different types of classes. A class may be Top level class, nested
class, derived class, super class, or an anonymous class.
1.1. Class Declaration and Modifiers
The class declaration starts with the “Modifier”. Sometimes a class may be declared
without “Modifier”. In case a “modifier” is present it is followed by keyword “class”, which is
followed by “class name”. The body of the class is enclosed between pair of curly braces { }.
The declaration of the class will be as follow:
Modifier 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
}
}
According to the convention of java language, a class name starts with Upper-Case latter.
In case if the class name contains more than one word, then all the words begin with Upper-Case
letters. Space is not allowed in the class name. There are certain rules to be followed for the
class name:
i. The class name should be simple and descriptive
ii. Class name should start with upper-case letter and should be nouns.
iii. Space in the class name is not allowed.
iv. Keywords cannot be used as class names.
1
1.2 Class Modifiers
The class modifiers are used to control the access to the class and its inheritance characteristics.
The Java has number of packages. The packages contain sub-packages and classes. The java has
various modifiers as follow:
Modifiers Description
No modifier/default The class declared without modifier is accessible to the classes in
the its own package.
public When a class is declared as public, it is accessible to all the classes
in all the packages.
private Class is accessible to other members of the Outer class
protected Class is accessible to other members of the Outer class as well as
by classes derived from the outer class.
final When a class is declared as final, it cannot be inherited.
The abstract class can contain abstract methods and non-abstract
abstract methods. The abstract methods contain method declaration, body
will be implemented by the derived class. Non-abstract method
contains body also.
2
1.4. Declaration of Class 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.
The new operator dynamically allocates (that is, allocates at run time) memory for an object
and returns a reference to it. The declaration of an object is similar to the declaration of primitive
type variable as stated below:
Class_name Object_name; // declare reference to object
Object_name = new classname ( ); // allocate an object
Both statements are combined into a single statement as given below:
Class_name Object_name = new classname ( );
Example: Test.java
class Area
{
int length;
int width; Output:
}
public class Test
{
public static void main(String args[])
{
Area a1;
a1=new Area();
a1.length=10;
a1.width=20;
double area1=a1.length*a1.width;
System.out.println("The Area of the Field is :"+area1);
}
}
2. Assigning an Object to Another Object
When an object of a class is assigned to another object of same class, the first object can access
the data and methods of second object. This can be understood from the following program:
Example, Output:
class AssignObjectToAnother
{
//instance variables
int length,width;
}
class Test
{
public static void main(String args[])
{
//create objects
AssignObjectToAnother f1=new AssignObjectToAnother();
AssignObjectToAnother f2=new AssignObjectToAnother();
//initialize instance variables of obj1 object
f1.length=25;
f1.width=40;
System.out.println("The width of f1 before assigning is :"+f1.width);
f2=f1;
3
f2.width=100;
System.out.println("The width of f2 is :"+f2.width);
System.out.println("The width of f1 is :"+f1.width);
}
}
In the above program two objects f1 and f2 are created from the same class. The instance
variables of object f1 are assigned. And later f1 is assigned to f2 object. The instance variable
‘width’ of f2 is assigned as f2.width=40. When we print the value of instance variable width of
both f1 and f2 after assignment it is printed as 100. But, before assignment the value of the
instance variable width of f1 is 40. From this we can understand that when an object a class is
assigned to another object of same class, both will be pointing the same memory, and hence both
objects instance variables values will be same.
4
2. Body that contains declarations and executable statements and are enclosed in curly
braces( { } .
The general syntax of method would be as follow:
modifier type method_name (type par1,type par2,….type parn) //Header
{
Statements here // Body of method
}
Modifier: Here, the modifier can be any one such as public, private, protected, final,
static, abstract etc.
Return type: The method return type can be any one of the primitive types such as int,
float, double, char or class type, and void.
Method name: The name of the method is an identifier.
Parameter list: The parameter list is enclosed in parentheses, and each parameter is
separated by the comma operator.
5
Example,
class PrivateMembers {
private int length,width; //private data members and instance variables
}
public class PrivateDemo {
public static void main(String arg[]) {
PrivateMembers pm=new PrivateMembers(); //create objects
pm.length=25; //accessing the private members outside the class
pm.width=40;
int area=pm.length*pm.width; //accessing private data
System.out.println("The area is :"+area);
}
}
Output:
However, with the help of the public method of the class, the private members can be
accessed.You can call the private method from outside the class by changing the runtime
behavior of the class. If we want to hide the methods from accessing by user outside the class,
then the methods are declared as private. If we want to access private method, it could be done
with the help of the public method. A call to the private method is made inside the public
method definition. This is shown in the following program
Exampe,
class PrivateDemo {
private int length, width; //private data members and instance variables
private void setSides(int l, int w) //private method
{ length=l; Output:
width=w;
}
public int area(int l, int w)
{
setSides(l,w); //call to the private method
return(length*width);
}
}
public class PrivateMembers {
public static void main(String arg[]) {
PrivateDemo p1=new PrivateDemo(); //create objects
//access public method here with object p1
System.out.println("The area of the Rectangle is :"+p1.area(4,5));
}}
6
6. Constructor Methods for Class
A constructor is a block of code similar to the method. It is called when an instance of
the class is created. It is a special type of method which is used to automatically initialize the
object. Every time an object is created using the new keyword, at least one constructor is called.
A constructor name must be the same as its class name and it should not return a value not
even void..
We have two types of constructors. They are default constructor and parameterized
constructor. The default construct cannot take any arguments. Whereas, the parameterized
constructor will take parameters. A Java constructor cannot be abstract, static, final, and
synchronized. At the time of calling constructor, memory for the object is allocated in the
memory.
Example, ConstructorExample.java
class BankAccount {
long accno;
String name;
String bankName;
String ifscCode;
float balance;
BankAccount(String bn, String ifsc,long ano,String n,float bal) // This is the constructor method
{
bankName=bn;
ifscCode=ifsc; Output:
accno=ano;
name=n;
balance=bal;
}
void displayAccountDetails() {
System.out.println("Name of Bank :"+bankName);
System.out.println("IFSC Code :"+ifscCode);
System.out.println("A/C Holder Name :"+name);
System.out.println("A/C No :"+accno);
System.out.println("Balance Amount :"+balance);
}
void withDraw(float withDrawAmt) {
if(balance>=withDrawAmt) {
balance=balance-withDrawAmt;
System.out.println("After Withdrawing the Balance Amount is :"+balance);
}
else
System.out.println("In sufficient founds available.......");
}
void deposit(float depositAmt) {
balance=balance+depositAmt;
}}
public class ConstructorExample {
public static void main(String args[]) {
// Parameterized Constructor method
BankAccount ac1=new BankAccount("SBI","SBIN0001009",741256526,"Karth",90000);
ac1.displayAccountDetails();
ac1.deposit(50000);
System.out.println("After depositing balance Amount is:"+ac1.balance);
ac1.withDraw(20000);
}}
7
7. Overloaded Constructor Methods or Constructor Overloading
In Java, we can overload constructors like methods. The name of all the overloaded
constructors will be same as class, but their parameters are different either in number or type or
order of parameters so that every constructor can perform a different task.
Here is a class called Box that defines three instance variables: width, height, and depth.
We will use this name to declare objects of type Box. We can write a code to measure the
surface area of a box and volume of the box. if you want to be able to initialize a cube by
specifying only one value that would be used for all three dimensions. The following program
will illustrate the overloaded constructor.
Example, OverloadConstructors.java
class Box {
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate an uninitialized box
height = -1;
depth = -1;
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
} Output:
// compute and return volume
double volume() {
return width * height * depth;
}
}
public class OverloadConstructors {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(5, 10, 8);
Box mybox2 = new Box();
Box mycube = new Box(4);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}}
8
8. Overloaded Methods or Method Overloading
Method overloading is also known as Compile-time Polymorphism, Static
Polymorphism, or Early binding in Java. If a class has multiple methods having same name
but different in parameters, it is known as Method Overloading. A method is a collection of
statements that are grouped together to perform an operation. Method overloading is used when
objects are required to perform similar tasks but using different input parameters. This is
similar to the constructor overloading.
Example, MetodOverloading.java
import java.util.*;
class Summation {
int sum(int a, int b) // Overloaded sum(). This sum takes two integer parameters
{
return (a + b);
}
float sum(float x, float y, float z) //Overloaded sum(). This sum takes three float parameters
{
return (x + y + z);
}
// Overloaded sum(). This sum takes four double parameters
double sum(double x, double y, double z, double k)
{
return (x + y + z + k);
}
} Output:
public class MetodOverloading {
public static void main(String args[])
{
Summation s = new Summation();
Scanner in = new Scanner(System.in);
System.out.println("Enter a value");
int a = in.nextInt();
System.out.println("Enter the b value");
int b = in.nextInt();
int sum1= s.sum(a, b);
System.out.println("Summation1:"+sum1);
System.out.println("Enter x value");
float x= in.nextFloat();
System.out.println("Enter the y value");
float y = in.nextFloat();
System.out.println("Enter the z value");
float z = in.nextFloat();
float sum2=s.sum(x,y,z);
System.out.println("Summation2:"+sum2);
double sum3=s.sum(10.5, 20.5, 25.0, 40.5);
System.out.println("Summation3:"+sum3);
}
}
9. Nested Classes
A nested class is the one which is defined inside another class. The class which is defined
in another class is called nested class, or inner class. The class in which another class is defined
is called enveloping class or outer class. The scope of the inner class is limited to the scope of
outer class. The inner class can be static or non-static class.
9
If the inner class is declared as static, it can be accessed without creating object an object
of outer class. If the inner class is declared as non-static, then we have to create object from the
outer class first, and create object of inner class, and then access the inner class object using the
outer class object.
Write a java program to demonstrate non-static Inner class? NestedClasses.java
class Outer
{
int length,width;
public void display(int l, int w)
{
length=l;
width=w;
Inner iner=new Inner(); //inner class object is created inside the outer class
iner.area();
}
class Inner //non-static Inner Class Output:
{
public void area()
{
int a=length*width;
System.out.println("The area is :"+a);
}
}
}
public class NestedClasses
{
public static void main(String arg[])
{
Outer ob1=new Outer(); //Create object from Outer class
ob1.display(10,20);
}
}
Important Points:
1. The inner class has access to all the outer class members.
2. The outer class doesn’t have direct access to inner class members. It is possible through
the reference of the inner class object.
3. The object of inner class may be declared in the scope of outer class.
4. The method of inner object may be accessed through the object of inner class by the
outer class object.
Static Nested Class:
It can access the static data members of outer class.
It cannot access non-static data members (data and methods).
Static class can be accessed by the outer class name.
Write a java program to demonstrate static Inner class?
class StaticNested Output:
{
static int length,width;
static class Inner //static Inner Class
{
10
width=w;
}
public void area()
{
int a=length*width;
System.out.println("The area is :"+a);
}
}
}
class StaticNestedClass
{
public static void main(String arg[])
{
//Inner class object is accessed using outer class name.
StaticNested.Inner i1=new StaticNested.Inner();
i1.getData(4,5);
i1.area();
}
}
10. Anonymous Class
We can write a class inside another class. This is called nesting of classes. It is possible
to create a nested class without giving any name. The nested class that doesn’t contain any name
is called “Anonymous Class”. The Syntax of the anonymous class will be as follow:
class AnonymousEx
{ public static void main(String args[])
{
Object1=new Type(parameters_list) { //defining the anonymous class
//body of the anonymous class
};
}
}
The anonymous classes usually extend super class or implement the interface. The
keywords ‘extends’ or ‘implements’ do not appear in the definition. Anonymous class is
used where the class has to be used only once.
Write a java program to demonstrate the Anonymous class by extending the super class.
class Person
{ void display()
{
System.out.println(“Welcome to SACET");
}
}
class AnonymousEx
{ public static void main(String args[])
{ //object creation
Person p=new Person() { //body of the anonymous class Output:
void display()
{
System.out.println(" Welcome to CSE");
}
}; //end of anonymous class
p.display(); //calling the display method
}
}
11
11. Local Class
A local class is declared in a block or method, and hence the scope of the Local class is
limited to the block or method in which it is defined. These classes can refer local variables or
parameters which are declared as final (constants).These are not visible outside the block or
method, and hence access modifiers such as public, private, and protected cannot be applied to
these classes.
Example, Write a java program to demonstrate Local Class. LocalDemo.java
class LocalDemo
{
public static void main(String arg[])
{
final double PI=3.14;
class LocalClass //Local Class Definition starts here Output:
{
void circleArea(int r)
{
double a=PI*r*r;
System.out.println("The area of Circle is :"+a);
}
}
12
ii. final method
When a method is declared with final keyword, it is called a final method. A final
method cannot be overridden. We must declare methods with the final keyword for
which we are required to follow the same implementation throughout all the derived
classes.
Example , Write a java program to demonstrate Final Method
class A { //A is super class
final void meth() { // final method
System.out.println("This is a final method.");
}
}
class B extends A { //B is sub class
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}}
Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do so,
a compile-time error will result.
iii. final class
When a class is declared with final keyword, it is called a final class. A final class cannot
be extended(inherited). Declaring a class as final implicitly declares all of its methods as
final, too.
For example, Write a java program to demonstrate Final class
final class A{
void dispA()
{
System.out.println("Method of class A");
}
}
class B extends A //here A cannot be inherited Output:
{
void dispB()
{
System.out.println("Method of class B");
}
}
class FinalTest {
public static void main(String arg[]) {
B b=new B();
b.dispA();
b.dispB();
}
}
13
• Syntax for declare the static method:
Access_modifier static void methodName()
{
// Method body
}
• The static variable and method is only accessible by class name.
Syntax: classname.variablename; classname.methodname();
Example for static variables and methods : Output:
public class StaticExample { Output:
static int num = 500; //static variable
static String str = “II CSE SACET";
static void display() // This is Static meth od
{
System.out.println("\nStatic number is " + num);
System.out.println("\nStatic string is " + str);
}
void nonstatic() // non-static method
{
display(); // Static method can also access in non static method
}
public static void main(String args[]) // main method
{
StaticExample obj = new StaticExample(); //object creation
obj.nonstatic(); // This is object to call non static function
StaticExample.display(); // static method can called directly without an obj
}
}
14
public static void main(String arg[]){
Factorial f=new Factorial();
Scanner in = new Scanner(System.in);
System.out.println("Enter the n valiue");
int num=in.nextInt();
System.out.println("Factorial of given Number: "+f.fact(num));
}
}
class Rectangle
{
int length,width; // instance variables
Rectangle(int length,int width) //local variables
{
this.length=length;
this.width=width;
}
void area()
{
System.out.println("The area of Rectangle is :"+(length*width));
15
}
} Output:
class ThisDemo
{
public static void main(String arg[])
{
Rectangle r=new Rectangle(5,4);
r.area();
}
}
16
void area (Test t ) //here t is object and its type is Test
{
int a=t.length*t.width; Output:
System.out.println("The area is:"+a);
}
}
class ObjectAsParameter {
public static void main(String args[]) {
Test t1=new Test(20,30);
t1.area(t1); //here t1 is an object and is passed as argument
}
}
18.Passing Arguments byValue and by Reference (or)Call by Value and Call by Reference
• When a method is defined with local variables, the values are passed by value, that is,
the values of actual arguments are copied to the formal parameters. The method may
manipulate these values without affecting the actual arguments. This is called passing
arguments by values.
• However, if a method is defined with parameters as Objects, and if method changes
values of the instance variables of the object, then the changed values are retained by the
object. That means, if the values are changed in parameters of the method, it will affect
the actual arguments also. This is called passing arguments through reference.
Write a java program to demonstrate the passing arguments by values.
class PassByValue {
void swap(int x,int y) //here x, and y are parameters
{
int temp; Output:
temp=x;
x=y;
y=temp;
}
}
class PassByValueTest {
public static void main(String arg[]) {
int a=5,b=6;
PassByValue pbv=new PassByValue();
System.out.printf("Before swap a=%d and b=%d\n",a,b);
pbv.swap(a,b); //here a and b are actual arguments
System.out.printf("After swap a=%d and b=%d\n",a,b);
}
}
Write a java program to demonstrate the passing arguments through reference.
class PassByReference {
int a,b; //instance variables
PassByReference(int m,int n) { //m and n are parameters of constructor
a=m; output:
b=n;
}
//here object is parameter
void swap(PassByReference pbr) {
17
pbr.b=temp;
}
}
class PassByRefTest {
public static void main(String arg[]){
PassByReference pbr=new PassByReference(5,6);
System.out.printf("Before swap a=%d and b=%d\n",pbr.a,pbr.b);
pbr.swap(pbr); //here pbr object is actual argument
System.out.printf("After swap a=%d and b=%d\n",pbr.a,pbr.b);
}
}
18
ST. ANN’S COLLEGE OF ENGINEERING &TECHNOLOGY :: CHIRALA
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
FAQs
Subject : OOPT JAVA Year/Sem: II B.Tech – I Sem
Academic Year: 2025-26 Regulation: R23
UNIT-2:
1. What is an Object? How to allocate memory for objects? How to assign the values to the
variables in the class during the time of creation of an object to that class? Explain with
an example.
2. What is the difference between ‘static’ and ‘non-static’ methods in JAVA? Describe the
usage of static members and nesting members with suitable example programs in java.
3. a) What is a Constructor? What is the main purpose of Constructors? How to invoke a
constructor in JAVA?
b) Write a java program to illustrate the Methods by passing arguments by Value and
passing arguments by reference.
4. a) Explain the use of ‘this’ keyword with an example.
b) Write about ‘Final’ keyword and explain with an example.
5. a) Explain the concept of Nesting of Methods with an example.
b) What is the importance of constructor? Write a java program to perform constructor
overloading. Can we use constructors with parameters? What kind of parameters can be
given? Explain with area of various geometric shapes example.
6. a) Design a class that represents a bank account and construct the methods to
i) Assign initial values
ii) Deposit an amount
iii) Withdraw amount after checking balance
iv) Display the name and balance.
b) Do you need to use static keyword for the above bank account program? Explain.
7. a) Write a program that shows an Employee class which contains various methods for
accessing employee’s personal information and methods for paying an employee.
8. a) Discuss the significance of Overriding Methods with a program.
b) Write a Java method to find minimum values in given two values.
9. a) Write a Java program to read a number of any lengths. Perform the addition and
subtraction on the largest and smallest digits of it.
b) Write a Java Program to find sum of natural numbers.
10. a) Compare the working of constructor overloading with method overloading.
b) Demonstrate method overriding with an example java program.
11. a) Compare the pass-by-value with the pass-by-reference method using an example.
b) Demonstrate Nested class concept with an example.
12. a) Develop a program to carry out withdrawal operations in ATM.
b) Develop a method that initializes the attributes of an object.
13. a) Develop a program to compute the GCD of two numbers using Recursion.
b) Is it possible to access Private members of a class? Justify your answer.
14. a) Define recursion. Discuss the advantages of recursion.
b) Is it possible to define a class within another class? Justify your answer.
19