0% found this document useful (0 votes)
6 views19 pages

Oopt Java Unit-2 Material

The document outlines the syllabus for Object-Oriented Programming through Java, focusing on classes, objects, methods, and access control. It covers class declaration, modifiers, class members, constructors, and method definitions, providing examples for clarity. Key concepts include the use of access modifiers, object assignment, and the distinction between instance and class variables.

Uploaded by

snonline786
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)
6 views19 pages

Oopt Java Unit-2 Material

The document outlines the syllabus for Object-Oriented Programming through Java, focusing on classes, objects, methods, and access control. It covers class declaration, modifiers, class members, constructors, and method definitions, providing examples for clarity. Key concepts include the use of access modifiers, object assignment, and the distinction between instance and class variables.

Uploaded by

snonline786
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/ 19

ST.

ANN’S COLLEGE OF ENGINEERING &TECHNOLOGY :: CHIRALA


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
OBJECT ORIENTED PROGRAMMING THROUGH JAVA (UNIT-2)
SYLLABUS:
Classes and Objects: Introduction, Class Declaration and Modifiers, Class Members,
Declaration of Class Objects, Assigning One Object to Another, Access Control for Class
Members, Accessing Private Members of Class, Constructor Methods for Class, Overloaded
Constructor Methods, Nested Classes, Final Class and Methods, Passing Arguments by Value
and by Reference, Keyword this.
Methods: Introduction, Defining Methods, Overloaded Methods, Overloaded Constructor
Methods, Class Objects as Parameters in Methods, Access Control, Recursive Methods, Nesting
of Methods, Overriding Methods, Attributes Final and Static.

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.

1.3. Class Members


The members that are declared inside the class are called class members. These members
include fields, methods, nested classes, and interfaces. The field can be instance variable and
class variable. The instance variables are belong to an object, and every object keeps a copy of
these variables. The class variables are declared with modifier static. These are not copied to
objects, they always stay with class. All the objects will share the class variables.
Example, Write a java Program to demonstrate the difference between instance variable
and class variable.
class EmpData { Output:
static int count=0;
String name;
int empid;
EmpData(String s,int n)
{
name=s;
empid=n;
count=count+1;
}
void display()
{
System.out.println("Employee name:"+name); //instance variable is accessed here
System.out.println("Employee Id :"+empid);
System.out.println("Number of Employees in the Company :"+count);
//class variable is accessed here
}
}
class ClassMembers
{
public static void main(String arg[]) {
EmpData emp1=new EmpData(" Herbert Schildt ",100);
emp1.display();
EmpData emp2=new EmpData(" Anitha Seth ",200);
emp2.display();
}
}

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.

3. Access Modifiers /Access Control for Class Members


The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. The access to the class members can be controlled by placing the suitable
modifier/access specifier before the member in the class definition. There are four types of Java
access modifiers:
1. private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default/No Modifier: The access level of a default modifier is only within the package.
It cannot be accessed from outside the package. If you do not specify any access level, it
will be the default.
3. protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
4. public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
Syntax: Access specifier type indentifier;
Example:
class AccessDemo {
private int a;
int b;
protected c;
public int d;
}
class AccessDemoMain {
public static void main(String[]args) {
a=10; //compile time error
b=20;
c=30;
d=40;
}
}

4. Defining Methods in a Class


In java, a method represents an action on data or it is the behaviour of an object and is
defined inside the class and interface. A method is defined inside the class and interface. A
method cannot be defined inside other method, but can be defined in a local class. The
execution of the method is done inside the class with main method. The method is called with
object inside the main method. A method definition contains two components:
1. Header that contains modifier, return type, method name, and list of parameters. The
parameters are enclosed in a pair of parentheses( ).

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.

Example: Write a java program to generate the Fibonacci Series 1, 1, 2, 3, 5, 8, 13 ……


import java.util.*;
class Fibonacci {
int i=1, j=1,count=2,k; //instance variables
void fib(int num)
{ System.out.println("Fibonacci Series:");
System.out.print(i+" "+j);
while(count<num)
{
k=i+j; Output:
System.out.print(" "+k);
i=j;
j=k;
count++;
}
if(count==num)
{
System.out.println();
System.out.println("nth digit:"+k);
}
}
}
public class FibonacciSeries {
public static void main(String args[])
{
Fibonacci f1=new Fibonacci();
Scanner in = new Scanner(System.in);
System.out.println("Enter range of n valiue");
int num=in.nextInt();
f1.fib(num);
}
}

5. Accessing the Private Members of a Class


A Java private keyword is an access modifier. It can be assigned to variables, methods,
and inner classes. It is the most restricted type of access modifier. Private members of a class,
whether it may be instance variable or method can be accessed by the other member of the same
class. The outside code cannot access the private members directly.

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
{

void getData(int l,int w)


{
length=l;

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);
}
}

//creating object from local class and calling the method


LocalClass lc=new LocalClass ();
lc.circleArea(2);
}
}

12. Attribute Final


final keyword is used in different contexts. First of all, final is a non access modifier applicable
only to a variable, a method, or a class. The java final keyword can be used in many context as
follows:
i. final variable
ii. final method
iii. final class
i. final variables
 When a variable is declared with the final keyword, its value can’t be modified,
essentially, a constant. If you make any variable as final, you cannot change the value of
final variable(It will be constant).
Example of final variable:
 There is a final variable speedlimit, we are going to change the value of this variable, but
It can't be changed because final variable once assigned a value can never be changed.
class BikeRace{
final int speedlimit=90; //final variable
void run()
{
speedlimit=100; // final variable value can’t be change
}
public static void main(String args[]){
BikeRace obj=new BikeRace();
obj.run();
}
}
Output: Compile time Error

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. Attribute Static or Static Variables and Methods


Any method that uses the static keyword is referred to as a static method. A static method
in Java is a method that is part of a class rather than an instance of that class. Static methods
have access to static variables without using the class’s object (instance). It doesn’t require an
object of the class. In both static and non-static methods, static methods can be accessed directly.
Static variables are initialized only once, at the start of the program execution. These variables
should be initialized first, before the initialization of any instance variables. When a method is
completed, all of its variables are normally deleted. Sometimes we need to store a variable even
after completion of method execution.
• Syntax for declare the static variable, static type variable = value;

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. Recursive Methods


• It is a technique of defining a method so that it calls itself in one of its statements inside
the body. It is invoked by itself. In some cases, the problem provides this opportunity as
shown below.
• Factorial n=n!=n*(n-1)*(n-2)*(n-3)…..*1
• This may be written as: Factorial n=n*Factorial(n-1)
Factorial 4 =4* Factorial(4-1)
=4*3* Factorial(3-1)
=4*3*2* Factorial(2-1)
=4*3*2* 1=24
Note: Factorial(0)->1, Factorial (1)->1 are the base cases.
Write a java program to demonstrate the Recursive method for finding the Factorial of a
given number.
import java.util.*;
class Factorial
{
int fact(int n) Output:
{
if (n==0 || n==1) //base case
return 1;
else
return (n*fact(n-1)); //calling fact() again
}
}
class RecursionDemo {

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));
}
}

15. Keyword this


• There may be a situation where the names of the local variables and the instance variable
names could be same. In such a context the local variables will hide the instance
variables.
• To access the instance variables in such a situation is done with the help of ‘this’
keyword. The ‘this’ keyword will provide the reference to the current object.
• The ‘this’ keyword is used before the instance variable with dot operator. (syntax:
this.instance_variable=local_variable;)

class Rectangle //to demonstrate the instance variables hiding.


{
int length,width; // instance variables
Rectangle(int length,int width) //local variables
{
length=length; //local variables are hiding instance variables
width=width;
}
void area()
{
System.out.println("The area of Rectangle is :"+(length*width));
}
}
class Hiding Output:
{
public static void main(String arg[])
{
Rectangle r=new Rectangle(5,4);
r.area();
}
}

// write a Java Program to demonstrate the ‘this’ keyword.

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. Nesting of Methods


• A method in a class can call another method in the same class. Since, a method calls
another method in the same class, dot (.) operator is not needed. A method can call any
number of methods.
• Successive calls can be made. That means, first method calls second method, second
method calls, third method and so on.
For example,
class Recctangle
{
int length, width; //instance variables
void setValues(int l, int w)
{
length=l;
width=w; Output:
}
void area(int len, int wid)
{
setValues(len,wid); // call to another method
int a=length*width;
System.out.println(" The area is :"+ a);
}
}
public class NestedMethods{
public static void main(String args[])
{
Recctangle r1=new Recctangle(); //create objects
r1.area(4,5));
}
}

17. Class Objects as Parameters in Methods


• Similar to any primitive type such as int, char, float, double, an object of a class also can
be passed as parameter to a method. The type of the parameter in this context is the name
of the class.
For example, Write a java program to demonstrate object as parameter.
class Test {
int length,width;
Test(int l, int w)
{
length=l;
width=w;
}

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) {

int temp; temp=pbr.a;


pbr.a=pbr.b;

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);
}
}

19. Overriding Methods or Method overriding


Method overriding is an example of runtime polymorphism. In method overriding, a
subclass overrides a method with the same signature as that of in its superclass. This feature
allows to uses the super class method as it is in the subclass. In some cases subclass may define
the same method that is defined in the super class, but with different behaviour or purpose. Then,
in that case, that method is said be overridden. The method defined in the subclass will be
executed and will hide the method of the super class.
For example ,
class Shape{
void draw(){
System.out.println("Drawing Shapes...");
}
}
class Rectangle extends Shape{
void draw(){ Output:
System.out.println("Drawing Rectangle...");
}
}
class Circle extends Shape{
void draw(){
System.out.println("Drawing Circle...");
}
}
class Triangle extends Shape{
void draw(){
System.out.println("Drawing Triangle...");
}
}
public class MethodOverriding{
public static void main(String args[]){
Shape s1;
s1=new Rectangle();
s1.draw();
s1=new Circle();
s1.draw();
s1=new Triangle();
s1.draw();
}
}

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

You might also like