5 Unit

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 63

UNIT-II

Passing and Returning Objects in Java


Although Java is strictly passed by value, the precise effect differs between whether
a primitive type or a reference type is passed. When we pass a primitive type to a method,
it is passed by value. But when we pass an object to a method, the situation changes
dramatically, because objects are passed by what is effectively call-by-reference. Java
does this interesting thing that’s sort of a hybrid between pass-by-value and pass-by-
reference.
Basically, a parameter cannot be changed by the function, but the function can ask the
parameter to change itself via calling some method within it.
 While creating a variable of a class type, we only create a reference to an object. Thus,
when we pass this reference to a method, the parameter that receives it will refer to the
same object as that referred to by the argument.
 This effectively means that objects act as if they are passed to methods by use of call-
by-reference.
 Changes to the object inside the method do reflect the object used as an argument.
Illustration: Let us suppose three objects ‘ob1’ , ‘ob2’ and ‘ob3’ are created:
ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob2 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);
Although Java is strictly passed by value, the precise effect differs between whether
a primitive type or a reference type is passed. When we pass a primitive type to a method,
it is passed by value. But when we pass an object to a method, the situation changes
dramatically, because objects are passed by what is effectively call-by-reference. Java
does this interesting thing that’s sort of a hybrid between pass-by-value and pass-by-
reference.
Basically, a parameter cannot be changed by the function, but the function can ask the
parameter to change itself via calling some method within it.
 While creating a variable of a class type, we only create a reference to an object. Thus,
when we pass this reference to a method, the parameter that receives it will refer to the
same object as that referred to by the argument.
 This effectively means that objects act as if they are passed to methods by use of call-
by-reference.
 Changes to the object inside the method do reflect the object used as an argument.
Illustration: Let us suppose three objects ‘ob1’ , ‘ob2’ and ‘ob3’ are created:
ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob2 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);
From the method side, a reference of type Foo with a name a is declared and it’s initially
assigned to null.

boolean equalTo(ObjectPassDemo o);

As we call the method equalTo, the reference ‘o’ will be assigned to the object which is
passed as an argument, i.e. ‘o’ will refer to ‘ob2’ as the following statement execute.
System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));
Now as we can see, equalTo method is called on ‘ob1’ , and ‘o’ is referring to ‘ob2’. Since
values of ‘a’ and ‘b’ are same for both the references, so if(condition) is true, so boolean
true will be return.
if(o.a == a && o.b == b)
Again ‘o’ will reassign to ‘ob3’ as the following statement execute.
System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));

 Now as we can see, the equalTo method is called on ‘ob1’ , and ‘o’ is referring to ‘ob3’.
Since values of ‘a’ and ‘b’ are not the same for both the references, so if(condition) is
false, so else block will execute, and false will be returned.
In Java we can pass objects to methods as one can perceive from the below program as
follows:
// Java Program to Demonstrate Objects Passing to Methods.

// Class
// Helper class
class ObjectPassDemo {
int a, b;

// Constructor
ObjectPassDemo(int i, int j)
{
a = i;
b = j;
}

// Method
boolean equalTo(ObjectPassDemo o)
{
// Returns true if o is equal to the invoking
// object notice an object is passed as an
// argument to method
return (o.a == a && o.b == b);
}
}

// Main class
public class GFG {
// MAin driver method
public static void main(String args[])
{
// Creating object of above class inside main()
ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob2 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);

// Checking whether object are equal as custom


// values
// above passed and printing corresponding boolean
// value
System.out.println("ob1 == ob2: "
+ ob1.equalTo(ob2));
System.out.println("ob1 == ob3: "
+ ob1.equalTo(ob3));
}
}
Output
ob1 == ob2: true
ob1 == ob3: false

Defining a constructor that takes an object of its class as a parameter

One of the most common uses of object parameters involves constructors. Frequently, in
practice, there is a need to construct a new object so that it is initially the same as some
existing object. To do this, either we can use Object.clone() method or define a
constructor that takes an object of its class as a parameter.
Example
// Java program to Demonstrate One Object to
// Initialize Another

// Class 1
class Box {
double width, height, depth;

// Notice this constructor. It takes an


// object of type Box. This constructor use
// one object to initialize another
Box(Box ob)
{
width = ob.width;
height = ob.height;
depth = ob.depth;
}

// constructor used when all dimensions


// specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}

// compute and return volume


double volume() { return width * height * depth; }
}

// MAin class
public class GFG {
// Main driver method
public static void main(String args[])
{
// Creating a box with all dimensions specified
Box mybox = new Box(10, 20, 15);

// Creating a copy of mybox


Box myclone = new Box(mybox);

double vol;

// Get volume of mybox


vol = mybox.volume();
System.out.println("Volume of mybox is " + vol);

// Get volume of myclone


vol = myclone.volume();
System.out.println("Volume of myclone is " + vol);
}
}
Output

Volume of mybox is 3000.0


Volume of myclone is 3000.0
Returning Objects
In java, a method can return any type of data, including objects. For example, in the
following program, the incrByTen( ) method returns an object in which the value of an (an
integer variable) is ten greater than it is in the invoking object.
Example
// Java Program to Demonstrate Returning of Objects

// Class 1
class ObjectReturnDemo {
int a;

// Constructor
ObjectReturnDemo(int i) { a = i; }

// Method returns an object


ObjectReturnDemo incrByTen()
{
ObjectReturnDemo temp
= new ObjectReturnDemo(a + 10);
return temp;
}
}

// Class 2
// Main class
public class GFG {

// Main driver method


public static void main(String args[])
{

// Creating object of class1 inside main() method


ObjectReturnDemo ob1 = new ObjectReturnDemo(2);
ObjectReturnDemo ob2;

ob2 = ob1.incrByTen();

System.out.println("ob1.a: " + ob1.a);


System.out.println("ob2.a: " + ob2.a);
}
}
Output
ob1.a: 2
ob2.a: 12

Recursion in Java
In Java, Recursion is a process in which a function calls itself directly or indirectly is called
recursion and the corresponding function is called a recursive function. Using a recursive
algorithm, certain problems can be solved quite easily. A few Java recursion examples
are Towers of Hanoi (TOH) , Inorder/Preorder/Postorder Tree Traversals , DFS of Graph,
etc.
Base Condition in Recursion
In the recursive program, the solution to the base case is provided and the solution to the
bigger problem is expressed in terms of smaller problems.
int fact(int n)
{
if (n < = 1) // base case
return 1;
else
return n*fact(n-1);
}
In the above example, the base case for n < = 1 is defined and the larger value of a
number can be solved by converting it to a smaller one till the base case is reached.
Working of Recursion
The idea is to represent a problem in terms of one or more smaller sub-problems and add
base conditions that stop the recursion. For example, we compute factorial n if we know
the factorial of (n-1). The base case for factorial would be n = 0. We return 1 when n = 0.

Java Recursion Programs


1. Factorial Using Recursion
The classic example of recursion is the computation of the factorial of a number.
The factorial of a number N is the product of all the numbers between 1 and N. The
below-given code computes the factorial of the numbers: 3, 4, and 5.
 3= 3 *2*1 (6)
 4= 4*3*2*1 (24)
 5= 5*3*2*1 (120)
Below is the implementation of the factorial:
// Java Program to implement
// Factorial using recursion
class GFG {

// recursive method
int fact(int n)
{
int result;

if (n == 1)
return 1;
result = fact(n - 1) * n;
return result;
}
}

// Driver Class
class Recursion {

// Main function
public static void main(String[] args)
{
GFG f = new GFG();

System.out.println("Factorial of 3 is "
+ f.fact(3));
System.out.println("Factorial of 4 is "
+ f.fact(4));
System.out.println("Factorial of 5 is "
+ f.fact(5));
}
}
Output

Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
2. Fibonacci Series
Fibonacci Numbers are the numbers is the integer sequence where Fib(N) = Fib(N-2) +
Fib(N-1). Below is the example to find 3,4,5.
 Fib(3) = Fib(2) + Fib(1) = Fib(1) + 0 + 1 = 1+1 = 2
 Fib(4) = Fib(3) + Fib(2) = 2+1 = 3
 Fib(5) = Fib(4) + Fib(3) = 3 + 2 = 5
Below is the implementation of the Fibonacci Series:
// Java Program to implement
// Fibonacci Series
import java.io.*;

// Driver Function
class GFG {

// Function to return Fibonacci value


static int Fib(int N)
{
if (N == 0 || N == 1)
return N;

return Fib(N - 1) + Fib(N - 2);


}

// Main function
public static void main(String[] args)
{
// Fibonacci of 3
System.out.println("Fibonacci of " + 3 + " "
+ Fib(3));

// Fibonacci of 4
System.out.println("Fibonacci of " + 4 + " "
+ Fib(4));
// Fibonacci of 3
System.out.println("Fibonacci of " + 5 + " "
+ Fib(5));
}
}
Output
Fibonacci of 3 2
Fibonacci of 4 3
Fibonacci of 5 5

Constructor overloading in Java


In Java, we can overload constructors like methods. The constructor overloading can be defined as the
concept of having more than one constructor with different parameters so that every constructor can
perform a different task.

Consider the following Java program, in which we have used different constructors in the class.

Example
1. public class Student {
2. //instance variables of the class
3. int id;
4. String name;
5.
6. Student(){
7. System.out.println("this a default constructor");
8. }
9.
10. Student(int i, String n){
11. id = i;
12. name = n;
13. }
14.
15. public static void main(String[] args) {
16. //object creation
17. Student s = new Student();
18. System.out.println("\nDefault Constructor values: \n");
19. System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);
20.
21. System.out.println("\nParameterized Constructor values: \n");
22. Student student = new Student(10, "David");
23. System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);
24. }
25. }

Output:

this a default constructor

Default Constructor values:

Student Id : 0
Student Name : null

Parameterized Constructor values:

Student Id : 10
Student Name : David

In the above example, the Student class constructor is overloaded with two different constructors, I.e.,
default and parameterized.

Here, we need to understand the purpose of constructor overloading. Sometimes, we need to use
multiple constructors to initialize the different values of the class.

We must also notice that the java compiler invokes a default constructor when we do not use any
constructor in the class. However, the default constructor is not invoked if we have used any constructor
in the class, whether it is default or parameterized. In this case, the java compiler throws an exception
saying the constructor is undefined.

Method Overloading in Java


In Java, Method Overloading allows different methods to have the same name, but
different signatures where the signature can differ by the number of input parameters or
type of input parameters, or a mixture of both.
Method overloading in Java is also known as Compile-time Polymorphism , Static
Polymorphism, or Early binding. In Method overloading compared to the parent
argument, the child argument will get the highest priority.
Example of Method Overloading
// Java program to demonstrate working of method
// overloading in Java

public class Sum {


// Overloaded sum(). This sum takes two int parameters
public int sum(int x, int y) { return (x + y); }
// Overloaded sum(). This sum takes three int parameters
public int sum(int x, int y, int z)
{
return (x + y + z);
}

// Overloaded sum(). This sum takes two double


// parameters
public double sum(double x, double y)
{
return (x + y);
}

// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
Output

30
60
31.0

Different Ways of Method Overloading in Java


 Changing the Number of Parameters.
 Changing Data Types of the Arguments.
 Changing the Order of the Parameters of Methods

1. Changing the Number of Parameters

Method overloading can be achieved by changing the number of parameters while


passing to different methods.
Below is the implementation of the above method:
// Java Program to Illustrate Method Overloading
// By Changing the Number of Parameters

// Importing required classes


import java.io.*;

// Class 1
// Helper class
class Product {
// Method 1
// Multiplying two integer values
public int multiply(int a, int b)
{
int prod = a * b;
return prod;
}

// Method 2
// Multiplying three integer values
public int multiply(int a, int b, int c)
{
int prod = a * b * c;
return prod;
}
}

// Class 2
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating object of above class inside main()
// method
Product ob = new Product();

// Calling method to Multiply 2 numbers


int prod1 = ob.multiply(1, 2);

// Printing Product of 2 numbers


System.out.println(
"Product of the two integer value :" + prod1);
// Calling method to multiply 3 numbers
int prod2 = ob.multiply(1, 2, 3);

// Printing product of 3 numbers


System.out.println(
"Product of the three integer value :" + prod2);
}
}
Output

Product of the two integer value :2


Product of the three integer value :6

2. Changing Data Types of the Arguments

In many cases, methods can be considered Overloaded if they have the same name but
have different parameter types, methods are considered to be overloaded.
Below is the implementation of the above method:
// Java Program to Illustrate Method Overloading
// By Changing Data Types of the Parameters

// Importing required classes


import java.io.*;

// Class 1
// Helper class
class Product {
// Multiplying three integer values
public int Prod(int a, int b, int c)
{
int prod1 = a * b * c;
return prod1;
}

// Multiplying three double values.


public double Prod(double a, double b, double c)
{
double prod2 = a * b * c;
return prod2;
}
}
class GFG {
public static void main(String[] args)
{
Product obj = new Product();

int prod1 = obj.Prod(1, 2, 3);


System.out.println(
"Product of the three integer value :" + prod1);

double prod2 = obj.Prod(1.0, 2.0, 3.0);


System.out.println(
"Product of the three double value :" + prod2);
}
}Output

Product of the three integer value :6


Product of the three double value :6.0

3. Changing the Order of the Parameters of Methods

Method overloading can also be implemented by rearranging the parameters of two or


more overloaded methods. For example, if the parameters of method 1 are (String name,
int roll_no) and the other method is (int roll_no, String name) but both have the same
name, then these 2 methods are considered to be overloaded with different sequences of
parameters.
Below is the implementation of the above method:
// Java Program to Illustrate Method Overloading
// By changing the Order of the Parameters

// Importing required classes


import java.io.*;

// Class 1
// Helper class
class Student {
// Method 1
public void StudentId(String name, int roll_no)
{
System.out.println("Name :" + name + " "
+ "Roll-No :" + roll_no);
}
// Method 2
public void StudentId(int roll_no, String name)
{
// Again printing name and id of person
System.out.println("Roll-No :" + roll_no + " "
+ "Name :" + name);
}
}

// Class 2
// Main class
class GFG {
// Main function
public static void main(String[] args)
{
// Creating object of above class
Student obj = new Student();

// Passing name and id


// Note: Reversing order
obj.StudentId("Spyd3r", 1);
obj.StudentId(2, "Kamlesh");
}
}Output

Name :Spyd3r Roll-No :1


Roll-No :2 Name :Kamlesh

static Keyword in Java


The static keyword in Java is mainly used for memory management. The static keyword
in Java is used to share the same variable or method of a given class. The users can
apply static keywords with variables, methods, blocks, and nested classes. The static
keyword belongs to the class than an instance of the class. The static keyword is used for
a constant variable or a method that is the same for every instance of a class.
The static keyword is a non-access modifier in Java that is applicable for the
following:
1. Blocks
2. Variables
3. Methods
4. Classes

Note: To create a static member(block, variable, method, nested class), precede its
declaration with the keyword static.
Characteristics of static keyword:

Here are some characteristics of the static keyword in Java:


 Shared memory allocation: Static variables and methods are allocated memory
space only once during the execution of the program. This memory space is shared
among all instances of the class, which makes static members useful for maintaining
global state or shared functionality.
 Accessible without object instantiation: Static members can be accessed without
the need to create an instance of the class. This makes them useful for providing utility
functions and constants that can be used across the entire program.
 Associated with class, not objects: Static members are associated with the class,
not with individual objects. This means that changes to a static member are reflected in
all instances of the class, and that you can access static members using the class
name rather than an object reference.
 Cannot access non-static members: Static methods and variables cannot access
non-static members of a class, as they are not associated with any particular instance
of the class.
 Can be overloaded, but not overridden: Static methods can be overloaded, which
means that you can define multiple methods with the same name but different
parameters. However, they cannot be overridden, as they are associated with the class
rather than with a particular instance of the class.
When a member is declared static, it can be accessed before any objects of its class are
created, and without reference to any object. For example, in the below java program, we
are accessing static method m1() without creating any object of the Test class.

// Java program to demonstrate that a static member

// can be accessed before instantiating a class

class Test

// static method

static void m1()

System.out.println("from m1");

}
public static void main(String[] args)

// calling m1 without creating

// any object of class Test

m1();

}
}Output

from m1
Static blocks
If you need to do the computation in order to initialize your static variables, you can
declare a static block that gets executed exactly once, when the class is first loaded.
Consider the following java program demonstrating the use of static blocks.

// Java program to demonstrate use of static blocks

class Test

// static variable

static int a = 10;

static int b;

// static block

static {

System.out.println("Static block initialized.");

b = a * 4;

}
public static void main(String[] args)

System.out.println("from main");

System.out.println("Value of a : "+a);

System.out.println("Value of b : "+b);

}
}Output

Static block initialized.


from main
Value of a : 10
Value of b : 40
For a detailed article on static blocks, see static blocks

Static variables

When a variable is declared as static, then a single copy of the variable is created and
shared among all objects at the class level. Static variables are, essentially, global
variables. All instances of the class share the same static variable.
Important points for static variables:
 We can create static variables at the class level only. See here
 static block and static variables are executed in the order they are present in a
program.
Below is the Java program to demonstrate that static block and static variables are
executed in the order they are present in a program.

 Java
// Java program to demonstrate execution
// of static blocks and variables

class Test
{
// static variable
static int a = m1();

// static block
static {
System.out.println("Inside static block");
}
// static method
static int m1() {
System.out.println("from m1");
return 20;
}

// static method(main !!)


public static void main(String[] args)
{
System.out.println("Value of a : "+a);
System.out.println("from main");
}
}
Output

from m1
Inside static block
Value of a : 20
from main

Static methods

When a method is declared with the static keyword, it is known as the static method. The
most common example of a static method is the main( ) method. As discussed above, Any
static member can be accessed before any objects of its class are created, and without
reference to any object. Methods declared as static have several restrictions:
 They can only directly call other static methods.
 They can only directly access static data.
 They cannot refer to this or super in any way.
Below is the java program to demonstrate restrictions on static methods.
// Java program to demonstrate restriction on static methods

class Test
{
// static variable
static int a = 10;

// instance variable
int b = 20;

// static method
static void m1()
{
a = 20;
System.out.println("from m1");
// Cannot make a static reference to the non-static field b
b = 10; // compilation error

// Cannot make a static reference to the


// non-static method m2() from the type Test
m2(); // compilation error

// Cannot use super in a static context


System.out.println(super.a); // compiler error
}

// instance method
void m2()
{
System.out.println("from m2");
}

public static void main(String[] args)


{
// main method
}
}Output:
prog.java:18: error: non-static variable b cannot be referenced from
a static context
b = 10; // compilation error
^
prog.java:22: error: non-static method m2() cannot be referenced from
a static context
m2(); // compilation error
^
prog.java:25: error: non-static variable super cannot be referenced
from a static context
System.out.println(super.a); // compiler error
^
prog.java:25: error: cannot find symbol
System.out.println(super.a); // compiler error
^
symbol: variable a
4 errors
When to use static variables and methods?

Use the static variable for the property that is common to all objects. For example, in class
Student, all students share the same college name. Use static methods for changing static
variables.
Consider the following java program, that illustrates the use of static keywords with
variables and methods.
// A java program to demonstrate use of
// static keyword with methods and variables

// Student class
class Student {
String name;
int rollNo;

// static variable
static String cllgName;

// static counter to set unique roll no


static int counter = 0;

public Student(String name)


{
this.name = name;

this.rollNo = setRollNo();
}

// getting unique rollNo


// through static variable(counter)
static int setRollNo()
{
counter++;
return counter;
}

// static method
static void setCllg(String name) { cllgName = name; }

// instance method
void getStudentInfo()
{
System.out.println("name : " + this.name);
System.out.println("rollNo : " + this.rollNo);

// accessing static variable


System.out.println("cllgName : " + cllgName);
}
}

// Driver class
public class StaticDemo {
public static void main(String[] args)
{
// calling static method
// without instantiating Student class
Student.setCllg("XYZ");

Student s1 = new Student("Alice");


Student s2 = new Student("Bob");

s1.getStudentInfo();
s2.getStudentInfo();
}
}

Output
name : Alice
rollNo : 1
cllgName : XYZ
name : Bob
rollNo : 2
cllgName : XYZ
Static Classes
A class can be made static only if it is a nested class. We cannot declare a top-level class
with a static modifier but can declare nested classes as static. Such types of classes are
called Nested static classes. Nested static class doesn’t need a reference of Outer class.
In this case, a static class cannot access non-static members of the Outer class.
// A java program to demonstrate use
// of static keyword with Classes

import java.io.*;

public class GFG {

private static String str = "GeeksforGeeks";

// Static class
static class MyNestedClass {

// non-static method
public void disp(){
System.out.println(str);
}
}

public static void main(String args[])


{
GFG.MyNestedClass obj
= new GFG.MyNestedClass();
obj.disp();
}
}Output

Here’s an example Java program that demonstrates the use of the static keyword:

public class ExampleClass {


public static int count = 0;
public int id;

public ExampleClass() {
count++;
id = count;
}

public static void printCount() {


System.out.println("Number of instances: " + count);
}
public void printId() {
System.out.println("Instance ID: " + id);
}

public static void main(String[] args) {


ExampleClass e1 = new ExampleClass();
ExampleClass e2 = new ExampleClass();
ExampleClass e3 = new ExampleClass();

e1.printId();
e2.printId();
e3.printId();

ExampleClass.printCount();
}
}

Advantages:

 Memory efficiency: Static members are allocated memory only once during the
execution of the program, which can result in significant memory savings for large
programs.
 Improved performance: Because static members are associated with the class rather
than with individual instances, they can be accessed more quickly and efficiently than
non-static members.
 Global accessibility: Static members can be accessed from anywhere in the program,
regardless of whether an instance of the class has been created.
 Encapsulation of utility methods: Static methods can be used to encapsulate utility
functions that don’t require any state information from an object. This can improve code
organization and make it easier to reuse utility functions across multiple classes.
 Constants: Static final variables can be used to define constants that are shared
across the entire program.
 Class-level functionality: Static methods can be used to define class-level
functionality that doesn’t require any state information from an object, such as factory
methods or helper functions.
Overall, the static keyword is a powerful tool that can help to improve the efficiency and
organization of your Java programs.

Nested Classes in Java


In Java, it is possible to define a class within another class, such classes are known as nested classes.
They enable you to logically group classes that are only used in one place, thus this increases the use
of encapsulation and creates more readable and maintainable code.
 The scope of a nested class is bounded by the scope of its enclosing class. Thus in the below
example, the class NestedClass does not exist independently of the class OuterClass.
 A nested class has access to the members, including private members, of the class in which it is
nested. But the enclosing class does not have access to the member of the nested class.
 A nested class is also a member of its enclosing class.
 As a member of its enclosing class, a nested class can be declared private, public, protected,
or package-private(default).
 Nested classes are divided into two categories:
1. static nested class: Nested classes that are declared static are called static nested classes.
2. inner class: An inner class is a non-static nested class.
Syntax:
class OuterClass
{
...
class NestedClass
{
...
}
}

Static nested classes


In the case of normal or regular inner classes, without an outer class object existing, there cannot be
an inner class object. i.e., an object of the inner class is always strongly associated with an outer class
object. But in the case of static nested class, Without an outer class object existing, there may be a
static nested class object. i.e., an object of a static nested class is not strongly associated with the
outer class object. As with class methods and variables, a static nested class is associated with its
outer class. And like static class methods, a static nested class cannot refer directly to instance
variables or methods defined in its enclosing class: it can use them only through an object reference.
They are accessed using the enclosing class name.
OuterClass.StaticNestedClass
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject =
new OuterClass.StaticNestedClass();
Below is the implementation of the above method:
// Java program to demonstrate accessing
// a static nested class

// outer class
class OuterClass {
// static member
static int outer_x = 10;

// instance(non-static) member
int outer_y = 20;

// private member
private static int outer_private = 30;

// static nested class


static class StaticNestedClass {
void display()
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);

// can access private static member of


// outer class
System.out.println("outer_private = "
+ outer_private);

// The following statement will give compilation


// error as static nested class cannot directly
// access non-static members
// System.out.println("outer_y = " + outer_y);

// Therefore create object of the outer class


// to access the non-static member
OuterClass out = new OuterClass();
System.out.println("outer_y = " + out.outer_y);

}
}
}
// Driver class
public class StaticNestedClassDemo {
public static void main(String[] args)
{
// accessing a static nested class
OuterClass.StaticNestedClass nestedObject
= new OuterClass.StaticNestedClass();

nestedObject.display();
}
}
Output

outer_x = 10
outer_private = 30
outer_y = 20

Inner classes
To instantiate an inner class, you must first instantiate the outer class. Then, create the
inner object within the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
There are two special kinds of inner classes :
1. Local inner classes
2. Anonymous inner classes
// Java program to demonstrate accessing
// a inner class

// outer class
class OuterClass {
// static member
static int outer_x = 10;

// instance(non-static) member
int outer_y = 20;

// private member
private int outer_private = 30;

// inner class
class InnerClass {
void display()
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);
// can also access non-static member of outer
// class
System.out.println("outer_y = " + outer_y);

// can also access a private member of the outer


// class
System.out.println("outer_private = "
+ outer_private);
}
}
}

// Driver class
public class InnerClassDemo {
public static void main(String[] args)
{
// accessing an inner class
OuterClass outerObject = new OuterClass();

OuterClass.InnerClass innerObject
= outerObject.new InnerClass();

innerObject.display();
}
}

Output
outer_x = 10
outer_y = 20
outer_private = 30

Java Command Line Arguments


The java command-line argument is an argument i.e. passed at the time of running the java program.

The arguments passed from the console can be received in the java program and it can be used as an
input.

So, it provides a convenient way to check the behavior of the program for the different values. You can
pass N (1,2,3 and so on) numbers of arguments from the command prompt.

Simple example of command-line argument in java


In this example, we are receiving only one argument and printing it. To run this java program, you must
pass at least one argument from the command prompt.

class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
Output: Your first argument is: sonoo

Java Inheritance
❮ PreviousNext ❯

Java Inheritance (Subclass and Superclass)


In Java, it is possible to inherit attributes and methods from one class to another. We group the
"inheritance concept" into two categories:

 subclass (child) - the class that inherits from another class


 superclass (parent) - the class being inherited from

To inherit from a class, use the extends keyword.

In the example below, the Car class (subclass) inherits the attributes and methods from
the Vehicle class (superclass):

Example
class Vehicle {

protected String brand = "Ford"; // Vehicle attribute

public void honk() { // Vehicle method

System.out.println("Tuut, tuut!");

class Car extends Vehicle {

private String modelName = "Mustang"; // Car attribute


public static void main(String[] args) {

// Create a myCar object

Car myCar = new Car();

// Call the honk() method (from the Vehicle class) on the myCar object

myCar.honk();

// Display the value of the brand attribute (from the Vehicle class) and the value of
the modelName from the Car class

System.out.println(myCar.brand + " " + myCar.modelName);

Access Modifiers in Java


in Java, Access modifiers help to restrict the scope of a class, constructor, variable,
method, or data member. It provides security, accessibility, etc to the user depending
upon the access modifier used with the element. Let us learn about Java Access
Modifiers, their types, and the uses of access modifiers in this article.
Types of Access Modifiers in Java
There are four types of access modifiers available in Java:
1. Default – No keyword required
2. Private
3. Protected
4. Public

1. Default Access Modifier


When no access modifier is specified for a class, method, or data member – It is said to be having
the default access modifier by default. The data members, classes, or methods that are not declared
using any access modifiers i.e. having default access modifiers are accessible only within the same
package.
In this example, we will create two packages and the classes in the packages will be having the
default access modifiers and we will try to access a class from one package from a class of the
second package.
// Java program to illustrate default modifier
package p1;

// Class Geek is having Default access modifier


class Geek
{
void display()
{
System.out.println("Hello World!");
}
}

// Java program to illustrate error while


// using class from different package with
// default modifier
package p2;
import p1.*;

// This class is having default access modifier


class GeekNew
{
public static void main(String args[])
{
// Accessing class Geek from package p1
Geek obj = new Geek();

obj.display();
}
}

Output:
Compile time error

2. Private Access Modifier


The private access modifier is specified using the keyword private. The methods or data
members declared as private are accessible only within the class in which they are
declared.
 Any other class of the same package will not be able to access these members.
 Top-level classes or interfaces can not be declared as private because
 private means “only visible within the enclosing class”.
 protected means “only visible within the enclosing class and any subclasses”
Hence these modifiers in terms of application to classes, apply only to nested classes and
not on top-level classes
In this example, we will create two classes A and B within the same package p1. We will
declare a method in class A as private and try to access this method from class B and see
the result.
// Java program to illustrate error while
// Using class from different package with

// Private Modifier
package p1;

// Class A
class A {
private void display()
{
System.out.println("GeeksforGeeks");
}
}

// Class B
class B {
public static void main(String args[])
{
A obj = new A();
// Trying to access private method
// of another class
obj.display();
}
}

Output:
error: display() has private access in A
obj.display();

3. Protected Access Modifier


The protected access modifier is specified using the keyword protected.
The methods or data members declared as protected are accessible within the same
package or subclasses in different packages.
In this example, we will create two packages p1 and p2. Class A in p1 is made public, to
access it in p2. The method display in class A is protected and class B is inherited from
class A and this protected method is then accessed by creating an object of class B.
Program 1:
// Java Program to Illustrate
// Protected Modifier
package p1;

// Class A
public class A {
protected void display()
{
System.out.println("GeeksforGeeks");
}
}
// Java program to illustrate
// protected modifier
package p2;

// importing all classes in package p1


import p1.*;

// Class B is subclass of A
class B extends A {
public static void main(String args[])
{
B obj = new B();
obj.display();
}
}

Output:
GeeksforGeeks
Public Access modifier
The public access modifier is specified using the keyword public.
 The public access modifier has the widest scope among all other access modifiers.
 Classes, methods, or data members that are declared as public are accessible from
everywhere in the program. There is no restriction on the scope of public data
members.
// Java program to illustrate
// public modifier
package p1;
public class A
{
public void display()
{
System.out.println("GeeksforGeeks");
}
}
package p2;
import p1.*;
class B {
public static void main(String args[])
{
A obj = new A();
obj.display();
}
}Output:
GeeksforGeeks
Important Points:
 If other programmers use your class, try to use the most restrictive access level that
makes sense for a particular member. Use private unless you have a good reason not
to.
 Avoid public fields except for constants.

Types of Inheritance in Java


Inheritance is the most powerful feature of object-oriented programming. It allows us to inherit the
properties of one class into another class. In this section, we will discuss types of inheritance in Java in-
depth with real-life examples. Also, we will create Java programs to implement the concept of different
types of inheritance.

Inheritance
Inheritance is a mechanism of driving a new class from an existing class. The existing (old) class is known
as base class or super class or parent class. The new class is known as a derived class or sub
class or child class. It allows us to use the properties and behavior of one class (parent) in another class
(child).

A class whose properties are inherited is known as parent class and a class that inherits the properties of
the parent class is known as child class. Thus, it establishes a relationship between parent and child class
that is known as parent-child or Is-a relationship.

Suppose, there are two classes named Father and Child and we want to inherit the properties of the
Father class in the Child class. We can achieve this by using the extends keyword.

1. //inherits the properties of the Father class


2. class Child extends Father
3. {
4. //functionality
5. }
When we should use inheritance?

Inheritance provides the reusability of code especially when there is a large scale of code to reuse. It also
establishes the relationship between different classes that is known as a Is-a relationship. We can also use
it if we want to achieve method overriding.

Points to Remember
o Constructor cannot be inherited in Java.
o Private members do not get inherited in Java.
o Cyclic inheritance is not permitted in Java.
o Assign parent reference to child objects.
o Constructors get executed because of super() present in the constructor.

Types of Inheritance
Java supports the following four types of inheritance:

o Single Inheritance
o Multi-level Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance

Note: Multiple inheritance is not supported in Java.

Let's discuss each with proper example.

Single Inheritance

In single inheritance, a sub-class is derived from only one super class. It inherits the properties and
behavior of a single-parent class. Sometimes it is also known as simple inheritance.

In the above figure, Employee is a parent class and Executive is a child class. The Executive class inherits all
the properties of the Employee class.

Let's implement the single inheritance mechanism in a Java program.

Executive.java

1. class Employee
2. {
3. float salary=34534*12;
4. }
5. public class Executive extends Employee
6. {
7. float bonus=3000*6;
8. public static void main(String args[])
9. {
10. Executive obj=new Executive();
11. System.out.println("Total salary credited: "+obj.salary);
12. System.out.println("Bonus of six months: "+obj.bonus);
13. }
14. }

Output:

Total salary credited: 414408.0


Bonus of six months: 18000.0

Multi-level Inheritance

In multi-level inheritance, a class is derived from a class which is also derived from another class is called
multi-level inheritance. In simple words, we can say that a class that has more than one parent class is
called multi-level inheritance. Note that the classes must be at different levels. Hence, there exists a single
base class and single derived class but multiple intermediate base classes.

In the above figure, the class Marks inherits the members or methods of the class Students. The class
Sports inherits the members of the class Marks. Therefore, the Student class is the parent class of the class
Marks and the class Marks is the parent of the class Sports. Hence, the class Sports implicitly inherits the
properties of the Student along with the class Marks.

Let's implement the multi-level inheritance mechanism in a Java program.

MultilevelInheritanceExample.java

1. //super class
2. class Student
3. {
4. int reg_no;
5. void getNo(int no)
6. {
7. reg_no=no;
8. }
9. void putNo()
10. {
11. System.out.println("registration number= "+reg_no);
12. }
13. }
14. //intermediate sub class
15. class Marks extends Student
16. {
17. float marks;
18. void getMarks(float m)
19. {
20. marks=m;
21. }
22. void putMarks()
23. {
24. System.out.println("marks= "+marks);
25. }
26. }
27. //derived class
28. class Sports extends Marks
29. {
30. float score;
31. void getScore(float scr)
32. {
33. score=scr;
34. }
35. void putScore()
36. {
37. System.out.println("score= "+score);
38. }
39. }
40. public class MultilevelInheritanceExample
41. {
42. public static void main(String args[])
43. {
44. Sports ob=new Sports();
45. ob.getNo(0987);
46. ob.putNo();
47. ob.getMarks(78);
48. ob.putMarks();
49. ob.getScore(68.7);
50. ob.putScore();
51. }
52. }

Output:

registration number= 0987


marks= 78.0
score= 68.7

Hierarchical Inheritance

If a number of classes are derived from a single base class, it is called hierarchical inheritance.

In the above figure, the classes Science, Commerce, and Arts inherit a single parent class named Student.
Let's implement the hierarchical inheritance mechanism in a Java program.

HierarchicalInheritanceExample.java

1. //parent class
2. class Student
3. {
4. public void methodStudent()
5. {
6. System.out.println("The method of the class Student invoked.");
7. }
8. }
9. class Science extends Student
10. {
11. public void methodScience()
12. {
13. System.out.println("The method of the class Science invoked.");
14. }
15. }
16. class Commerce extends Student
17. {
18. public void methodCommerce()
19. {
20. System.out.println("The method of the class Commerce invoked.");
21. }
22. }
23. class Arts extends Student
24. {
25. public void methodArts()
26. {
27. System.out.println("The method of the class Arts invoked.");
28. }
29. }
30. public class HierarchicalInheritanceExample
31. {
32. public static void main(String args[])
33. {
34. Science sci = new Science();
35. Commerce comm = new Commerce();
36. Arts art = new Arts();
37. //all the sub classes can access the method of super class
38. sci.methodStudent();
39. comm.methodStudent();
40. art.methodStudent();
41. }
42. }

Output:

The method of the class Student invoked.


The method of the class Student invoked.
The method of the class Student invoked.

Hybrid Inheritance

Hybrid means consist of more than one. Hybrid inheritance is the combination of two or more types of
inheritance.

In the above figure, GrandFather is a super class. The Father class inherits the properties of the
GrandFather class. Since Father and GrandFather represents single inheritance. Further, the Father class is
inherited by the Son and Daughter class. Thus, the Father becomes the parent class for Son and Daughter.
These classes represent the hierarchical inheritance. Combinedly, it denotes the hybrid inheritance.

Let's implement the hybrid inheritance mechanism in a Java program.

Daughter.java

1. //parent class
2. class GrandFather
3. {
4. public void show()
5. {
6. System.out.println("I am grandfather.");
7. }
8. }
9. //inherits GrandFather properties
10. class Father extends GrandFather
11. {
12. public void show()
13. {
14. System.out.println("I am father.");
15. }
16. }
17. //inherits Father properties
18. class Son extends Father
19. {
20. public void show()
21. {
22. System.out.println("I am son.");
23. }
24. }
25. //inherits Father properties
26. public class Daughter extends Father
27. {
28. public void show()
29. {
30. System.out.println("I am a daughter.");
31. }
32. public static void main(String args[])
33. {
34. Daughter obj = new Daughter();
35. obj.show();
36. }
37. }

Output:

I am daughter.

Super Keyword in Java


The super keyword in Java is a reference variable that is used to refer to parent class
when we’re working with objects. You need to know the basics
of Inheritanceand Polymorphism to understand the Java super keyword.
The Keyword “super” came into the picture with the concept of Inheritance. In this article,
we gonna covers all about super in Java including definitions, examples, Uses, Syntax,
and more.
Table of Content
 Characteristics of Super Keyword in Java
 Use of super keyword in Java
 1. Use of super with Variables
 2. Use of super with Methods
 3. Use of super with constructors
 Advantages of Using Java Super Keyword
Characteristics of Super Keyword in Java
In Java, super keyword is used to refer to the parent class of a subclass. Here are some
of its key characteristics:
 super is used to call a superclass constructor: When a subclass is created, its
constructor must call the constructor of its parent class. This is done using the super()
keyword, which calls the constructor of the parent class.
 super is used to call a superclass method: A subclass can call a method defined in
its parent class using the super keyword. This is useful when the subclass wants to
invoke the parent class’s implementation of the method in addition to its own.
 super is used to access a superclass field: A subclass can access a field defined in
its parent class using the super keyword. This is useful when the subclass wants to
reference the parent class’s version of a field.
 super must be the first statement in a constructor: When calling a superclass
constructor, the super() statement must be the first statement in the constructor of the
subclass.
 super cannot be used in a static context: The super keyword cannot be used in a
static context, such as in a static method or a static variable initializer.
 super is not required to call a superclass method: While it is possible to use the
super keyword to call a method in the parent class, it is not required. If a method is not
overridden in the subclass, then calling it without the super keyword will invoke the
parent class’s implementation.
Overall, the super keyword is a powerful tool for subclassing in Java, allowing
subclasses to inherit and build upon the functionality of their parent classes.
Use of super keyword in Java
It is majorly used in the following contexts as mentioned below:
 Use of super with Variables
 Use of super with Methods
 Use of super with Constructors
1. Use of super with Variables
This scenario occurs when a derived class and base class have the same data members.
In that case, there is a possibility of ambiguity r the JVM.
We can understand it more clearly using the following example:
Example
// super keyword in java example

// Base class vehicle


class Vehicle {
int maxSpeed = 120;
}

// sub class Car extending vehicle


class Car extends Vehicle {
int maxSpeed = 180;

void display()
{
// print maxSpeed of base class (vehicle)
System.out.println("Maximum Speed: "
+ super.maxSpeed);
}
}

// Driver Program
class Test {
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}

Output

Maximum Speed: 120


In the above example, both the base class and subclass have a member maxSpeed. We
could access the maxSpeed of the base class in subclass using super keyword.
2. Use of super with Methods
This is used when we want to call the parent class method. So whenever a parent and
child class have the same-named methods then to resolve ambiguity we use the super
keyword.
This code snippet helps to understand the said usage of the super keyword.
Example
// super keyword in java example

// superclass Person
class Person {
void message()
{
System.out.println("This is person class\n");
}
}
// Subclass Student
class Student extends Person {
void message()
{
System.out.println("This is student class");
}
// Note that display() is
// only in Student class
void display()
{
// will invoke or call current
// class message() method
message();

// will invoke or call parent


// class message() method
super.message();
}
}
// Driver Program
class Test {
public static void main(String args[])
{
Student s = new Student();

// calling display() of Student


s.display();
}
}

Output

This is student class


This is person class
In the above example, we have seen that if we only call method message() then, the
current class message() is invoked but with the use of the super keyword, message() of
the superclass could also be invoked.
3. Use of super with constructors
The super keyword can also be used to access the parent class constructor. One more
important thing is that ‘super’ can call both parametric as well as non-parametric
constructors depending on the situation.
Following is the code snippet to explain the above concept:
Example 1
// Java Code to show use of
// super keyword with constructor

// superclass Person
class Person {
Person()
{
System.out.println("Person class Constructor");
}
}

// subclass Student extending the Person class


class Student extends Person {
Student()
{
// invoke or call parent class constructor
super();

System.out.println("Student class Constructor");


}
}

// Driver Program
class Test {
public static void main(String[] args)
{
Student s = new Student();
}
}
Output
Person class Constructor
Student class Constructor
In the above example, we have called the superclass constructor using the keyword
‘super’ via subclass constructor.
Example 2
class ParentClass {
public boolean isTrue() { return true; }
}

class ChildClass extends ParentClass {


public boolean isTrue()
{
// calls parent implementation of isTrue()
boolean parentResult = super.isTrue();
// negates the parent result
return !parentResult;
}
}

public class Main {


public static void main(String[] args)
{
ChildClass child = new ChildClass();
// calls child implementation
// of isTrue()
boolean result = child.isTrue();

// prints "false"
System.out.println(result);
}
}

Output

false
Advantages of Using Java Super Keyword
The super keyword in Java provides many advantages in object-oriented programming
are as follows:
 Enables reuse of code: Using the super keyword allows subclasses to inherit
functionality from their parent classes, which promotes the reuse of code and reduces
duplication.
 Supports polymorphism: Because subclasses can override methods and access
fields from their parent classes using super, polymorphism is possible. This allows for
more flexible and extensible code.
 Provides access to parent class behaviour: Subclasses can access and use
methods and fields defined in their parent classes through the super keyword, which
allows them to take advantage of existing behaviour without having to reimplement it.
 Allows for customization of behaviour: By overriding methods and using super to
call the parent implementation, subclasses can customize and extend the behaviour of
their parent classes.
 Facilitates abstraction and encapsulation: The use of super promotes encapsulation
and abstraction by allowing subclasses to focus on their behaviour while relying on the
parent class to handle lower-level details.

Method Overriding in Java


If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has been declared
by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
o Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Understanding the problem without method overriding

Let's understand the problem that we may face in the program if we don't use method overriding.

1. //Java Program to demonstrate why we need method overriding


2. //Here, we are calling the method of parent class with child
3. //class object.
4. //Creating a parent class
5. class Vehicle{
6. void run(){System.out.println("Vehicle is running");}
7. }
8. //Creating a child class
9. class Bike extends Vehicle{
10. public static void main(String args[]){
11. //creating an instance of child class
12. Bike obj = new Bike();
13. //calling the method with child class instance
14. obj.run();
15. }
16. }

Output:
Vehicle is running

Problem is that I have to provide a specific implementation of run() method in subclass that is why we use
method overriding.
Example of method overriding

In this example, we have defined the run method in the subclass as defined in the parent class but it has
some specific implementation. 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. //Java Program to illustrate the use of Java Method Overriding


2. //Creating a parent class.
3. class Vehicle{
4. //defining a method
5. void run(){System.out.println("Vehicle is running");}
6. }
7. //Creating a child class
8. class Bike2 extends Vehicle{
9. //defining the same method as in the parent class
10. void run(){System.out.println("Bike is running safely");}
11.
12. public static void main(String args[]){
13. Bike2 obj = new Bike2();//creating object
14. obj.run();//calling method
15. }
16. }

17. Output:

18. Bike is running safely


Dynamic Method Dispatch or Runtime Polymorphism in
Java
Method overriding is one of the ways in which Java supports Runtime Polymorphism.
Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time.
 When an overridden method is called through a superclass reference, Java determines
which version(superclass/subclasses) of that method is to be executed based upon the
type of the object being referred to at the time the call occurs. Thus, this determination
is made at run time.
 At run-time, it depends on the type of the object being referred to (not the type of the
reference variable) that determines which version of an overridden method will be
executed
 A superclass reference variable can refer to a subclass object. This is also known as
upcasting. Java uses this fact to resolve calls to overridden methods at run time.
Therefore, if a superclass contains a method that is overridden by a subclass, then when different
types of objects are referred to through a superclass reference variable, different versions of the
method are executed. Here is an example that illustrates dynamic method dispatch:
// A Java program to illustrate Dynamic Method
// Dispatch using hierarchical inheritance
class A
{
void m1()
{
System.out.println("Inside A's m1 method");
}
}

class B extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside B's m1 method");
}
}

class C extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside C's m1 method");
}
}

// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();
// object of type B
B b = new B();

// object of type C
C c = new C();

// obtain a reference of type A


A ref;

// ref refers to an A object


ref = a;

// calling A's version of m1()


ref.m1();

// now ref refers to a B object


ref = b;

// calling B's version of m1()


ref.m1();

// now ref refers to a C object


ref = c;

// calling C's version of m1()


ref.m1();
}
}Output:
Inside A's m1 method
Inside B's m1 method
Inside C's m1 method
Explanation :
The above program creates one superclass called A and it’s two subclasses B and C. These
subclasses overrides m1( ) method.
1. Inside the main() method in Dispatch class, initially objects of type A, B, and C are declared.
2. A a = new A(); // object of type A
3. B b = new B(); // object of type B
4. C c = new C(); // object of type C
5. Now a reference of type A, called ref, is also declared, initially it will point to null.
6. A ref; // obtain a reference of type A

1. Now we are assigning a reference to each type of object (either A’s or B’s or C’s)
to ref, one-by-one, and uses that reference to invoke m1( ). As the output shows, the
version of m1( ) executed is determined by the type of object being referred to at
the time of the call.
2. ref = a; // r refers to an A object
3. ref.m1(); // calling A's version of m1()

ref = b; // now r refers to a B object


ref.m1(); // calling B's version of m1()
ref = c; // now r refers to a C object
ref.m1(); // calling C's version of m1()

Runtime Polymorphism with Data Members


In Java, we can override methods only, not the variables(data members), so runtime
polymorphism cannot be achieved by data members. For example :
// Java program to illustrate the fact that
// runtime polymorphism cannot be achieved
// by data members

// class A
class A
{
int x = 10;
}

// class B
class B extends A
{
int x = 20;
}

// Driver class
public class Test
{
public static void main(String args[])
{
A a = new B(); // object of type B

// Data member of class A will be accessed


System.out.println(a.x);
}
}

Output:
10
Explanation : In above program, both the class A(super class) and B(sub class) have a
common variable ‘x’. Now we make object of class B, referred by ‘a’ which is of type of
class A. Since variables are not overridden, so the statement “a.x” will always refer to
data member of super class.
Advantages of Dynamic Method Dispatch
1. Dynamic method dispatch allow Java to support overriding of methods which is central
for run-time polymorphism.
2. It allows a class to specify methods that will be common to all of its derivatives, while
allowing subclasses to define the specific implementation of some or all of those
methods.
3. It also allow subclasses to add its specific methods subclasses to define the specific
implementation of some.
Static vs Dynamic binding
 Static binding is done during compile-time while dynamic binding is done during run-
time.
 private, final and static methods and variables uses static binding and bonded by
compiler while overridden methods are bonded during runtime based upon type of
runtime object

Abstract class in Java


A class which is declared with the abstract keyword is known as an abstract class in Java. It can have
abstract and non-abstract methods (method with the body).
Before learning the Java abstract class, let's understand the abstraction in Java first.

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Another way, it shows only essential things to the user and hides the internal details, for example, sending
SMS where you type the text and send the message. You don't know the internal processing about the
message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method implemented. It cannot be instantiated.

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the method.
Example of abstract class

1. abstract class A{}

Abstract Method in Java


A method which is declared as abstract and does not have implementation is known as an abstract
method.

1. abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract method

In this example, Bike is an abstract class that contains only one abstract method run. Its implementation is
provided by the Honda class.
1. abstract class Bike{
2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }

running safely

Understanding the real scenario of Abstract class


In this example, Shape is the abstract class, and its implementation is provided by the Rectangle and
Circle classes.

Mostly, we don't know about the implementation class (which is hidden to the end user), and an object of
the implementation class is provided by the factory method.

A factory method is a method that returns the instance of the class. We will learn about the factory
method later.

In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be
invoked.

File: TestAbstraction1.java

1. abstract class Shape{


2. abstract void draw();
3. }
4. //In real scenario, implementation is provided by others i.e. unknown by end user
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle1 extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. }
11. //In real scenario, method is called by programmer or user
12. class TestAbstraction1{
13. public static void main(String args[]){
14. Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape() method
15. s.draw();
16. }
17. }

drawing circle

final Keyword in Java


The final method in Java is used as a non-access modifier applicable only to
a variable, a method, or a class. It is used to restrict a user in Java.
The following are different contexts where the final is used:
1. Variable
2. Method
3. Class

Characteristics of final keyword in Java:


In Java, the final keyword is used to indicate that a variable, method, or class cannot be
modified or extended. Here are some of its characteristics:
 Final variables: When a variable is declared as final, its value cannot be changed
once it has been initialized. This is useful for declaring constants or other values that
should not be modified.
 Final methods: When a method is declared as final, it cannot be overridden by a
subclass. This is useful for methods that are part of a class’s public API and should not
be modified by subclasses.
 Final classes: When a class is declared as final, it cannot be extended by a subclass.
This is useful for classes that are intended to be used as is and should not be modified
or extended.
 Initialization: Final variables must be initialized either at the time of declaration or in
the constructor of the class. This ensures that the value of the variable is set and
cannot be changed.
 Performance: The use of a final can sometimes improve performance, as the compiler
can optimize the code more effectively when it knows that a variable or method cannot
be changed.
 Security: The final can help improve security by preventing malicious code from
modifying sensitive data or behavior.
Overall, the final keyword is a useful tool for improving code quality and ensuring that
certain aspects of a program cannot be modified or extended. By declaring variables,
methods, and classes as final, developers can write more secure, robust, and
maintainable code.

Java Final Variable


When a variable is declared with the final keyword, its value can’t be changed,
essentially, a constant. This also means that you must initialize a final variable.
If the final variable is a reference, this means that the variable cannot be re-bound to
reference another object, but the internal state of the object pointed by that reference
variable can be changed i.e. you can add or remove elements from the final array or final
collection.
It is good practice to represent final variables in all uppercase, using underscore to
separate words.
public class ConstantExample {
public static void main(String[] args) {
// Define a constant variable PI
final double PI = 3.14159;

// Print the value of PI


System.out.println("Value of PI: " + PI);
}
}
Output
Value of PI: 3.14159
Output:
Value of PI: 3.14159

Object class in Java


The Object class is the parent class of all the classes in java by default. In other words, it is the topmost
class of java.

The Object class is beneficial if you want to refer any object whose type you don't know. Notice that
parent class reference variable can refer the child class object, know as upcasting.

Let's take an example, there is getObject() method that returns an object but it can be of any type like
Employee,Student etc, we can use Object class reference to refer that object. For example:

1. Object obj=getObject();//we don't know what object will be returned from this method

The Object class provides some common behaviors to all the objects such as object can be compared,
object can be cloned, object can be notified etc.
Methods of Object class
The Object class provides many methods. They are as follows:

Method Description

public final Class getClass() returns the Class class object of this object. The Class
class can further be used to get the metadata of this
class.

public int hashCode() returns the hashcode number for this object.

public boolean equals(Object obj) compares the given object to this object.

protected Object clone() throws creates and returns the exact copy (clone) of this object.
CloneNotSupportedException

public String toString() returns the string representation of this object.

public final void notify() wakes up single thread, waiting on this object's monitor.

public final void notifyAll() wakes up all the threads, waiting on this object's
monitor.

public final void wait(long timeout)throws causes the current thread to wait for the specified
InterruptedException milliseconds, until another thread notifies (invokes
notify() or notifyAll() method).

public final void wait(long timeout,int causes the current thread to wait for the specified
nanos)throws InterruptedException milliseconds and nanoseconds, until another thread
notifies (invokes notify() or notifyAll() method).

public final void wait()throws causes the current thread to wait, until another thread
InterruptedException notifies (invokes notify() or notifyAll() method).

protected void finalize()throws Throwable is invoked by the garbage collector before object is
being garbage collected.

You might also like