OOPJ(java) Unit-II
OOPJ(java) Unit-II
Simple Example
class Ex1
{
int a;
public static void main(String args[])
{
Ex1 e = new Ex1();
e.a = 10;
System.out.println(" number= "+e.a);
}
}
Output: number=10
Class Object
No memory is allocated at the time of Sufficient memory space will be allocated for all
2
declaration the variables of class at the time of declaration.
System.out.println("Static variable staticVar: " + a); // using static variable within static method
class TestStudent4
{
public static void main (String args[])
{
Student s1 = new Student();
Student s2 = new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
As you can see in the above figure, object gets the memory in heap memory area.
The reference variable refers to the object allocated in the heap memory area.
Here, s1 and s2 both are reference variables that refer to the objects allocated in memory.
2.3 Assigning One Object to Another
In Java, assigning one object to another involves copying the reference(address) of the object, not the
object itself.
This means that both references (addresses) will point to the same object in memory, so changes made
through one reference will be reflected in the other.
Example:
class Student1
{
int rollno;
String name; // String is a class name is object type of variable
void insertRecord(int r , String n)
{
rollno = r;
name = n;
}
void displayInformation()
{
System.out.println(rollno+" "+name);
}
}
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
s1.displayInformation();
s2.displayInformation();
}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\cseb_codes>javac TestStudent5.java
D:\acem 2024-25 OOPJ CSE A&B\cseb_codes>java TestStudent5
111 Karan
222 Aryan
111 sunil
111 sunil
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
The first data column indicates whether the class itself has access to the member defined by the access
level.
As you can see, a class always has access to its own members.
The second column indicates whether classes in the same package as the class (regardless of their
parentage) have access to the member.
The third column indicates whether subclasses of the class declared outside this package have access to
the member.
The fourth column indicates whether all classes have access to the member.
Let's look at a collection of classes and see how access levels affect visibility. The following figure shows the
four classes in this example and how they are related.
The following table shows where the members of the Alpha class are visible for each of the access modifiers
that can be applied to them.
Visibility
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
double area()
{
return length*width;
}
double getLength()
{
return length;
}
double getWidth()
{
return width;
}
}
class AccessPrivateTechnique
{
public static void main(String[] args)
{
Farm f = new Farm();
f.setSides(50.0,20.0);
System.out.println("length = "+f.getLength()); // accessing private variable
System.out.println("length = "+f.getWidth()); // accessing private variable
System.out.println("area = "+f.area());
}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>javac AccessPrivateTechnique.java
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java AccessPrivateTechnique
length = 50.0
length = 20.0
area = 1000.0
double getLength()
{
return length;
}
double getWidth()
{
return width;
}
double getArea()
{
return area();
}
}
class AccessPrivateTechnique2
{
public static void main(String[] args)
{
Farm1 f = new Farm1();
f.setSides(50.0,20.0);
System.out.println("length = "+f.getLength());
System.out.println("length = "+f.getWidth());
System.out.println("area = "+f.getArea());
}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>javac AccessPrivateTechnique2.java
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java AccessPrivateTechnique2
length = 50.0
length = 20.0
area = 1000.0
Default Constructor
A constructor is said to be default constructor if and only if it never take any parameters.
If any class does not contain at least one user defined constructor than the system will create a default
constructor at the time of compilation it is known as system defined default constructor.
Syntax
class className
{
className () // Call default constructor
{
Block of statements; // Initialization
}
}
Note:
System defined default constructor is created by java compiler and does not have any statement in the body
part.
This constructor will be executed every time whenever an object is created if that class does not contain any
user defined constructor.
parameterized constructor
If any constructor contain list of variable in its signature is known as paremetrized constructor.
A parameterized constructor is one which takes some parameters.
Syntax
class ClassName
{
ClassName(list of parameters) //parameterized constructor
{
.......
}
.......
}
Syntax : ClassName objref = new ClassName(value1, value2,.....);
class ClassName
{
ClassName()
{
..........
}
ClassName(datatype1 value1)
{
.......
}
ClassName(datatype1 value1, datatype2 value2)
{
.......
}
ClassName(datatype2 variable2)
{
.......
}
}
ConstructorOverloading(int a , int b)
{
System.out.println("addition of integers with 2 params ="+(a+b));
ConstructorOverloading(double a , double b)
{
System.out.println("addition of doubles with 2 params ="+(a+b));
}
ConstructorOverloading(String a , String b)
{
System.out.println("addition of strings with 2 params ="+(a+b));
}
Example :
class Bike
{
final void run()
{
System.out.println("running");
}
}
Example:
class CallByReference
{
int a, b;
public class B
{
public static void main(String[] args)
{
CallByReference object = new CallByReference(10, 20);
System.out.println("Value of a: " + object.a+ " & b: "+ object.b);
object.ChangeValue(object);// Changing values in class function
System.out.println("Value of a: " + object.a + " & b: "+ object.b); // print values after calling
}
}
Output:
Value of a: 10 & b: 20
Value of a: 20 & b: 40
Please note that when we pass a reference, a new reference variable to the same object is created.
So we can only change members of the object whose reference is passed. We cannot change the reference to
refer to some other object as the received reference is a copy of the original reference.
class A
{
void m()
{
System.out.println("hello m");
}
void n()
{
System.out.println("hello n");
//m(); //same as this.m()
this.m();
}
}
class TestThis4
{
public static void main(String args[])
{
A a = new A();
a.n();
}
}
Output:
hello n
hello m
The this() constructor call can be used to invoke the current class constructor.
It is used to reuse the constructor. In other words, it is used for constructor chaining.
Rule: Call to this() must be the first statement in constructor.
class A
{
A()
{
this(5);
System.out.println("hello a");
}
A(int x)
{
System.out.println(x);
}
}
class TestThis6
{
public static void main(String args[])
{
A a=new A();
}
}
Output:
5
hello a
Method Declaration
Method Signature:
Every method has a method signature. It is a part of the method declaration.
It includes the method name and parameter list.
Return Type:
Return type is a data type that the method returns.
It may have a primitive data type, object, collection, void, etc.
If the method does not return anything, we use void keyword.
Method Name:
It is a unique name that is used to define the name of a method.
Parameter List:
It is the list of parameters separated by a comma and enclosed in the pair of parentheses.
It contains the data type and variable name.
If the method has no parameter, left the parentheses blank.
Method Body:
It is a part of the method declaration.
It contains all the actions to be performed. It is enclosed within the pair of curly braces.
Predefined Methods
As the name gives it, predefined methods in Java are the ones that the Java class libraries already define.
This means that they can be called and used anywhere in our program without defining them.
There are many predefined methods, such as length(), sqrt(), max(), and print(), and each of them is
defined inside their respective classes.
Output:
The Square root is : 5
Demo.java
public class Demo
{
public static void main(String[] args)
{
System.out.print("The maximum number is: " + Math.max(9,7)); // using max() method of Math class
}
}
Output: The maximum number is: 9
//Example1
class A
{
int a,b,c;
void sum()
{
a=10;
b=20;
c=a+b;
System.out.println(" c= "+c);
}
}
class B
{
public static void main(String ars[])
{
A e = new A();
e.sum();
}
}
Output:
c=30
class Addition
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(float a, float b)
{
System.out.println(a+b);
}
// Constructor
public ObjectParameter(int attribute1, String attribute2, double attribute3)
{
this.attribute1 = attribute1;
this.attribute2 = attribute2;
this.attribute3 = attribute3;
}
directRecFun();
// Some code...
}
Indirect recursion:
void indirectRecFun1()
{
// Some code...
indirectRecFun2();
// Some code...
}
void indirectRecFun2()
{
// Some code...
indirectRecFun1();
// Some code...
}
Syntax:
returntype methodname()
{
//code to be executed
methodname();//calling same method
}
int area(int a, int y) // Method to calculate the area of a rectangle, using the perimeter method
{
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>javac NestingMethodsExample.java
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java NestingMethodsExample
Length of the rectangle: 3
Breadth of the rectangle: 4
Height of the cuboid: 5
Perimeter: 28
Area: 12
Volume: 60
class Vehicle
{
void run()
{
System.out.println(" Vehicle is running ");
}
}
Problem is that I have to provide my own implementation for run() method in subclass that is why we use
method overriding.
The name and parameter of the method are the same, and there is IS-A relationship between the classes, so there
is method overriding.
1) Method overloading is used to increase the Method overriding is used to provide the specific
readability of the program. implementation of the method that is already provided by
its super class.
2) Method overloading is performed within Method overriding occurs in two classesthat have IS-A
class. (inheritance) relationship.
3) In method overloading, parameter must be In case of method overriding, parameter must be same.
different.
4) Method overloading is the example Method overriding is the example of run time
of compile time polymorphism. polymorphism.
5) In java, method overloading can't be Return type must be same or covariant in method
performed by changing return type of the overriding.
method only. Return type can be same or
Object Oriented Programming Through Java Page 37
different in method overloading. But you
2.20 Attributes Final and Static
Attributes Final
The final keyword in java is used to restrict the user.
The java final keyword can be used in many context.
final can be used for variables or methods or classes
Java final variable
If you make any variable as final, you cannot change the value of final variable (It will be constant).
Example:
class Bike9
{
final int speedlimit = 90; //final variable
void run()
{
speedlimit = 400;
}
public static void main(String args[])
{
Bike9 obj = new Bike9();
obj.run();
}
}
Output: Compile Time Error
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 ExampleStatic
{
}
}
Output :