5 Unit
5 Unit
5 Unit
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);
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;
// 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);
double vol;
// Class 1
class ObjectReturnDemo {
int a;
// Constructor
ObjectReturnDemo(int i) { a = i; }
// Class 2
// Main class
public class GFG {
ob2 = ob1.incrByTen();
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.
// 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 {
// 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
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:
Student Id : 0
Student Name : null
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.
// 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
// 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();
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
// 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;
}
// 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();
Note: To create a static member(block, variable, method, nested class), precede its
declaration with the keyword static.
Characteristics of static keyword:
class Test
// static method
System.out.println("from m1");
}
public static void main(String[] args)
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.
class Test
// static variable
static int b;
// static block
static {
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 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;
}
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
// instance method
void m2()
{
System.out.println("from m2");
}
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;
this.rollNo = setRollNo();
}
// 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);
// Driver class
public class StaticDemo {
public static void main(String[] args)
{
// calling static method
// without instantiating Student class
Student.setCllg("XYZ");
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.*;
// Static class
static class MyNestedClass {
// non-static method
public void disp(){
System.out.println(str);
}
}
Here’s an example Java program that demonstrates the use of the static keyword:
public ExampleClass() {
count++;
id = count;
}
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.
// 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;
}
}
}
// 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);
// 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
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.
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 ❯
In the example below, the Car class (subclass) inherits the attributes and methods from
the Vehicle class (superclass):
Example
class Vehicle {
System.out.println("Tuut, tuut!");
// 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
obj.display();
}
}
Output:
Compile time error
// 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();
// Class A
public class A {
protected void display()
{
System.out.println("GeeksforGeeks");
}
}
// Java program to illustrate
// protected modifier
package p2;
// 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.
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.
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
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.
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:
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.
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:
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:
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.
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.
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
// 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();
Output
// superclass Person
class Person {
Person()
{
System.out.println("Person 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; }
}
// 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.
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
Let's understand the problem that we may face in the program if we don't use method overriding.
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.
17. Output:
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();
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()
// 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
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
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.
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
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
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
drawing circle
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 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.