0% found this document useful (0 votes)
72 views

Cluster 3

This document discusses inheritance in C++. It defines inheritance as a process where a derived class acquires the properties and behaviors of its base class. It describes different types of inheritance in C++ including single, multiple, hierarchical, multilevel, and hybrid inheritance. It provides examples of single inheritance where a derived class inherits fields and methods from a base class. It also discusses derived classes, private and public inheritance, and multilevel inheritance with an example. The document concludes with descriptions of multiple inheritance and resolving ambiguities that can occur with multiple inheritance.

Uploaded by

Poosarla Gayatri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views

Cluster 3

This document discusses inheritance in C++. It defines inheritance as a process where a derived class acquires the properties and behaviors of its base class. It describes different types of inheritance in C++ including single, multiple, hierarchical, multilevel, and hybrid inheritance. It provides examples of single inheritance where a derived class inherits fields and methods from a base class. It also discusses derived classes, private and public inheritance, and multilevel inheritance with an example. The document concludes with descriptions of multiple inheritance and resolving ambiguities that can occur with multiple inheritance.

Uploaded by

Poosarla Gayatri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Unit 3(Cluster 3)

C++ Inheritance
In C++, inheritance is a process in which one object acquires all the properties and
behaviors of its parent object automatically. In such way, you can reuse, extend or
modify the attributes and behaviors which are defined in other class.

In C++, the class which inherits the members of another class is called derived class
and the class whose members are inherited is called base class. The derived class is the
specialized class for the base class.

Advantage of C++ Inheritance


Code reusability: Now you can reuse the members of your parent class. So, there is
no need to define the member again. So less code is required in the class.

Types Of Inheritance
C++ supports five types of inheritance:

o Single inheritance

o Multiple inheritance

o Hierarchical inheritance

o Multilevel inheritance

o Hybrid inheritance
Derived Classes
A Derived class is defined as the class derived from the base class.

The Syntax of Derived class:

class derived_class_name : visibility-mode base_class_name


{
// body of the derived class.
}

Where,

derived_class_name: It is the name of the derived class.

visibility mode: The visibility mode specifies whether the features of the base class
are publicly inherited or privately inherited. It can be public or private.

base_class_name: It is the name of the base class.

o When the base class is privately inherited by the derived class, public members
of the base class becomes the private members of the derived class. Therefore,
the public members of the base class are not accessible by the objects of the
derived class only by the member functions of the derived class.

o When the base class is publicly inherited by the derived class, public members of
the base class also become the public members of the derived class. Therefore,
the public members of the base class are accessible by the objects of the derived
class as well as by the member functions of the base class.

Note:

o In C++, the default mode of visibility is private.

o The private members of the base class are never inherited.

C++ Single Inheritance


Single inheritance is defined as the inheritance in which a derived class is inherited
from the only one base class.

Where 'A' is the base class, and 'B' is the derived class.

C++ Single Level Inheritance Example: Inheriting Fields


When one class inherits another class, it is known as single level inheritance. Let's see
the example of single level inheritance which inherits the fields only.

1. #include <iostream>
2. using namespace std;
3. class Account {
4. public:
5. float salary = 60000;
6. };
7. class Programmer: public Account {
8. public:
9. float bonus = 5000;
10. };
11. int main(void) {
12. Programmer p1;
13. cout<<"Salary: "<<p1.salary<<endl;
14. cout<<"Bonus: "<<p1.bonus<<endl;
15. return 0;
16. }
Output:
Salary: 60000
Bonus: 5000

In the above example, Employee is the base class and Programmer is


the derived class.

C++ Single Level Inheritance Example: Inheriting


Methods
Let's see another example of inheritance in C++ which inherits methods only.

1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat() {
6. cout<<"Eating..."<<endl;
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void bark(){
13. cout<<"Barking...";
14. }
15. };
16. int main(void) {
17. Dog d1;
18. d1.eat();
19. d1.bark();
20. return 0;
21. }

Output:

Eating...
Barking...

Let's see a simple example.

1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. int a = 4;
6. int b = 5;
7. public:
8. int mul()
9. {
10. int c = a*b;
11. return c;
12. }
13. };
14.
15. class B : private A
16. {
17. public:
18. void display()
19. {
20. int result = mul();
21. std::cout <<"Multiplication of a and b is : "<<result<< std::endl;
22. }
23. };
24. int main()
25. {
26. B b;
27. b.display();
28.
29. return 0;
30. }

Output:

Multiplication of a and b is : 20

In the above example, class A is privately inherited. Therefore, the mul() function of
class 'A' cannot be accessed by the object of class B. It can only be accessed by the
member function of class B.

How to make a Private Member Inheritable


The private member is not inheritable. If we modify the visibility mode by making it
public, but this takes away the advantage of data hiding.

C++ introduces a third visibility modifier, i.e., protected. The member which is
declared as protected will be accessible to all the member functions within the class as
well as the class immediately derived from it.

Visibility modes can be classified into three categories:

o Public: When the member is declared as public, it is accessible to all the


functions of the program.

o Private: When the member is declared as private, it is accessible within the


class only.

o Protected: When the member is declared as protected, it is accessible within its


own class as well as the class immediately derived from it.
Visibility of Inherited Members

Base class visibility Derived class visibility

Public Private Protected

Private Not Inherited Not Inherited Not Inherited

Protected Protected Private Protected

Public Public Private Protected

C++ Multilevel Inheritance


Multilevel inheritance is a process of deriving a class from another derived class.

C++ Multi Level Inheritance Example


When one class inherits another class which is further inherited by another class, it is
known as multi level inheritance in C++. Inheritance is transitive so the last derived
class acquires all the members of all its base classes.
Let's see the example of multi level inheritance in C++.

1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat() {
6. cout<<"Eating..."<<endl;
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void bark(){
13. cout<<"Barking..."<<endl;
14. }
15. };
16. class BabyDog: public Dog
17. {
18. public:
19. void weep() {
20. cout<<"Weeping...";
21. }
22. };
23. int main(void) {
24. BabyDog d1;
25. d1.eat();
26. d1.bark();
27. d1.weep();
28. return 0;
29. }

Output:

Eating...
Barking...
Weeping...
C++ Multiple Inheritance
Multiple inheritance is the process of deriving a new class that inherits the attributes
from two or more classes.

Syntax of the Derived class:

1. class D : visibility B-1, visibility B-2, ?


2. {
3. // Body of the class;
4. }

Let's see a simple example of multiple inheritance.

1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. protected:
6. int a;
7. public:
8. void get_a(int n)
9. {
10. a = n;
11. }
12. };
13.
14. class B
15. {
16. protected:
17. int b;
18. public:
19. void get_b(int n)
20. {
21. b = n;
22. }
23. };
24. class C : public A,public B
25. {
26. public:
27. void display()
28. {
29. std::cout << "The value of a is : " <<a<< std::endl;
30. std::cout << "The value of b is : " <<b<< std::endl;
31. cout<<"Addition of a and b is : "<<a+b;
32. }
33. };
34. int main()
35. {
36. C c;
37. c.get_a(10);
38. c.get_b(20);
39. c.display();
40.
41. return 0;
42. }

Output:

The value of a is : 10
The value of b is : 20
Addition of a and b is : 30

In the above example, class 'C' inherits two base classes 'A' and 'B' in a public mode.
Ambiquity Resolution in Inheritance
Ambiguity can be occurred in using the multiple inheritance when a function with the
same name occurs in more than one base class.

Let's understand this through an example:

1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. public:
6. void display()
7. {
8. std::cout << "Class A" << std::endl;
9. }
10. };
11. class B
12. {
13. public:
14. void display()
15. {
16. std::cout << "Class B" << std::endl;
17. }
18. };
19. class C : public A, public B
20. {
21. void view()
22. {
23. display();
24. }
25. };
26. int main()
27. {
28. C c;
29. c.display();
30. return 0;
31. }

Output:

error: reference to 'display' is ambiguous


display();

o The above issue can be resolved by using the class resolution operator with the
function. In the above example, the derived class code can be rewritten as:

1. class C : public A, public B


2. {
3. void view()
4. {
5. A :: display(); // Calling the display() function of class A.
6. B :: display(); // Calling the display() function of class B.
7.
8. }
9. };

An ambiguity can also occur in single inheritance.

Consider the following situation:

1. class A
2. {
3. public:
4. void display()
5. {
6. cout<<?Class A?;
7. }
8. } ;
9. class B
10. {
11. public:
12. void display()
13. {
14. cout<<?Class B?;
15. }
16. } ;

In the above case, the function of the derived class overrides the method of the base
class. Therefore, call to the display() function will simply call the function defined in the
derived class. If we want to invoke the base class function, we can use the class
resolution operator.

1. int main()
2. {
3. B b;
4. b.display(); // Calling the display() function of B class.
5. b.B :: display(); // Calling the display() function defined in B class.
6. }

C++ Hybrid Inheritance


Hybrid inheritance is a combination of more than one type of inheritance.

Let's see a simple example:

1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. protected:
6. int a;
7. public:
8. void get_a()
9. {
10. std::cout << "Enter the value of 'a' : " << std::endl;
11. cin>>a;
12. }
13. };
14.
15. class B : public A
16. {
17. protected:
18. int b;
19. public:
20. void get_b()
21. {
22. std::cout << "Enter the value of 'b' : " << std::endl;
23. cin>>b;
24. }
25. };
26. class C
27. {
28. protected:
29. int c;
30. public:
31. void get_c()
32. {
33. std::cout << "Enter the value of c is : " << std::endl;
34. cin>>c;
35. }
36. };
37.
38. class D : public B, public C
39. {
40. protected:
41. int d;
42. public:
43. void mul()
44. {
45. get_a();
46. get_b();
47. get_c();
48. std::cout << "Multiplication of a,b,c is : " <<a*b*c<< std::endl;
49. }
50. };
51. int main()
52. {
53. D d;
54. d.mul();
55. return 0;
56. }

Output:

Enter the value of 'a' :


10
Enter the value of 'b' :
20
Enter the value of c is :
30
Multiplication of a,b,c is : 6000
C++ Hierarchical Inheritance
Hierarchical inheritance is defined as the process of deriving more than one class from a
base class.

Syntax of Hierarchical inheritance:

1. class A
2. {
3. // body of the class A.
4. }
5. class B : public A
6. {
7. // body of class B.
8. }
9. class C : public A
10. {
11. // body of class C.
12. }
13. class D : public A
14. {
15. // body of class D.
16. }

Let's see a simple example:

1. #include <iostream>
2. using namespace std;
3. class Shape // Declaration of base class.
4. {
5. public:
6. int a;
7. int b;
8. void get_data(int n,int m)
9. {
10. a= n;
11. b = m;
12. }
13. };
14. class Rectangle : public Shape // inheriting Shape class
15. {
16. public:
17. int rect_area()
18. {
19. int result = a*b;
20. return result;
21. }
22. };
23. class Triangle : public Shape // inheriting Shape class
24. {
25. public:
26. int triangle_area()
27. {
28. float result = 0.5*a*b;
29. return result;
30. }
31. };
32. int main()
33. {
34. Rectangle r;
35. Triangle t;
36. int length,breadth,base,height;
37. std::cout << "Enter the length and breadth of a rectangle: " << std::endl;
38. cin>>length>>breadth;
39. r.get_data(length,breadth);
40. int m = r.rect_area();
41. std::cout << "Area of the rectangle is : " <<m<< std::endl;
42. std::cout << "Enter the base and height of the triangle: " << std::endl;
43. cin>>base>>height;
44. t.get_data(base,height);
45. float n = t.triangle_area();
46. std::cout <<"Area of the triangle is : " << n<<std::endl;
47. return 0;
48. }

Output:

Enter the length and breadth of a rectangle:


23
20
Area of the rectangle is : 460
Enter the base and height of the triangle:
2
5
Area of the triangle is : 5
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).

The idea behind inheritance in Java is that you can create new classes that are built
upon existing classes. When you inherit from an existing class, you can reuse methods
and fields of the parent class. Moreover, you can add new methods and fields in your
current class also.

Inheritance represents the IS-A relationship which is also known as a parent-


child relationship.

Why use inheritance in java

o For Method Overriding (so runtime polymorphism can be achieved).

o For Code Reusability.

Terms used in Inheritance

o Class: A class is a group of objects which have common properties. It is a


template or blueprint from which objects are created.

o Sub Class/Child Class: Subclass is a class which inherits the other class. It is
also called a derived class, extended class, or child class.

o Super Class/Parent Class: Superclass is the class from where a subclass


inherits the features. It is also called a base class or a parent class.

o Reusability: As the name specifies, reusability is a mechanism which facilitates


you to reuse the fields and methods of the existing class when you create a new
class. You can use the same fields and methods already defined in the previous
class.

The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass,


and the new class is called child or subclass.

Java Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. The relationship between the two classes is Programmer IS-A Employee.
It means that Programmer is a type of Employee.

1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
Programmer salary is:40000.0
Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as
of Employee class i.e. code reusability.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface


only. We will learn about interfaces later.

When one class inherits multiple classes, it is known as multiple inheritance. For
Example:
Note: Multiple inheritance is not supported in Java through class.

Single Inheritance Example


When a class inherits another class, it is known as a single inheritance. In the example
given below, Dog class inherits the Animal class, so there is the single inheritance.

File: TestInheritance.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}

Output:

barking...
eating...

Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example
given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a
multilevel inheritance.

File: TestInheritance2.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}

Output:

weeping...
barking...
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical inheritance.
In the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.

File: TestInheritance3.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}

Output:

meowing...
eating...

Q) Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B
classes. If A and B classes have the same method and you call it from child class
object, there will be ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time
error if you inherit 2 classes. So whether you have same method or different, there will
be compile time error.

1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. public static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }

Compile Time Error

Aggregation in Java
If a class have an entity reference, it is known as Aggregation. Aggregation represents
HAS-A relationship.

Consider a situation, Employee object contains many informations such as id, name,
emailId etc. It contains one more object named address, which contains its own
informations such as city, state, country, zipcode etc. as given below.

1. class Employee{
2. int id;
3. String name;
4. Address address;//Address is a class
5. ...
6. }

In such case, Employee has an entity reference address, so relationship is Employee


HAS-A address.
Why use Aggregation?

o For Code Reusability.

Simple Example of Aggregation

In this example, we have created the reference of Operation class in the Circle class.

1. class Operation{
2. int square(int n){
3. return n*n;
4. }
5. }
6.
7. class Circle{
8. Operation op;//aggregation
9. double pi=3.14;
10.
11. double area(int radius){
12. op=new Operation();
13. int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
14. return pi*rsquare;
15. }
16.
17.
18.
19. public static void main(String args[]){
20. Circle c=new Circle();
21. double result=c.area(5);
22. System.out.println(result);
23. }
24. }

Output:78.5

When use Aggregation?

o Code reuse is also best achieved by aggregation when there is no is-a


relationship.

o Inheritance should be used only if the relationship is-a is maintained throughout


the lifetime of the objects involved; otherwise, aggregation is the best choice.

Understanding meaningful example of Aggregation


In this example, Employee has an object of Address, address object contains its own
informations such as city, state, country etc. In such case relationship is Employee
HAS-A address.

Address.java
1. public class Address {
2. String city,state,country;
3.
4. public Address(String city, String state, String country) {
5. this.city = city;
6. this.state = state;
7. this.country = country;
8. }
9.
10. }
Emp.java
1. public class Emp {
2. int id;
3. String name;
4. Address address;
5.
6. public Emp(int id, String name,Address address) {
7. this.id = id;
8. this.name = name;
9. this.address=address;
10. }
11.
12. void display(){
13. System.out.println(id+" "+name);
14. System.out.println(address.city+" "+address.state+" "+address.country);
15. }
16.
17. public static void main(String[] args) {
18. Address address1=new Address("gzb","UP","india");
19. Address address2=new Address("gno","UP","india");
20.
21. Emp e=new Emp(111,"varun",address1);
22. Emp e2=new Emp(112,"arun",address2);
23.
24. e.display();
25. e2.display();
26.
27. }
28. }

Output:111 varun
gzb UP india
112 arun
gno UP india
Function Overriding in C++
Function overriding is a feature that allows us to have a same function in child
class which is already present in the parent class. A child class inherits the data
members and member functions of parent class, but when you want to override a
functionality in the child class then you can use function overriding. It is like
creating a new version of an old function, in the child class.

Function Overriding Example


To override a function you must have the same signature in child class. By
signature I mean the data type and sequence of parameters. Here we don’t have
any parameter in the parent function so we didn’t use any parameter in the child
function.

#include <iostream>
using namespace std;
class BaseClass {
public:
void disp(){
cout<<"Function of Parent Class";
}
};
class DerivedClass: public BaseClass{
public:
void disp() {
cout<<"Function of Child Class";
}
};
int main() {
DerivedClass obj = DerivedClass();
obj.disp();
return 0;
}

Output:

Function of Child Class

Note: In function overriding, the function in parent class is called the overridden
function and function in child class is called overriding function.
How to call overridden function from the child
class
As we have seen above that when we make the call to function (involved in
overriding), the child class function (overriding function) gets called. What if you
want to call the overridden function by using the object of child class. You can do
that by creating the child class object in such a way that the reference of parent
class points to it. Lets take an example to understand it.

#include <iostream>
using namespace std;
class BaseClass {
public:
void disp(){
cout<<"Function of Parent Class";
}
};
class DerivedClass: public BaseClass{
public:
void disp() {
cout<<"Function of Child Class";
}
};
int main() {
/* Reference of base class pointing to
* the object of child class.
*/
BaseClass obj = DerivedClass();
obj.disp();
return 0;
}
Output:

Function of Parent Class

If you want to call the Overridden function from overriding function then you can
do it like this:

parent_class_name::function_name
To do this in the above example, we can write following statement in the disp()
function of child class:

BaseClass::disp();
Example 2: C++ Call Overridden Function From Derived Class

// C++ program to call the overridden function


// from a member function of the derived class

#include <iostream>
using namespace std;

class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};

class Derived : public Base {


public:
void print() {
cout << "Derived Function" << endl;

// call overridden function


Base::print();
}
};

int main() {
Derived derived1;
derived1.print();
return 0;
}

Output

Derived Function
Base Function

In this program, we have called the overridden function inside


the Derived class itself.
Notice the code Base::print(); , which calls the overridden function inside
the Derived class.
Example 3: C++ Call Overridden Function Using Pointer

// C++ program to access overridden function using pointer


// of Base type that points to an object of Derived class

#include <iostream>
using namespace std;

class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};

class Derived : public Base {


public:
void print() {
cout << "Derived Function" << endl;
}
};

int main() {
Derived derived1;

// pointer of Base type that points to derived1


Base* ptr = &derived1;

// call function of Base class using ptr


ptr->print();

return 0;
}

Output

Base Function

In this program, we have created a pointer of Base type named ptr . This
pointer points to the Derived object derived1 .

// pointer of Base type that points to derived1


Base* ptr = &derived1;

When we call the print() function using ptr , it calls the overridden function
from Base .

// call function of Base class using ptr


ptr->print();

This is because even though ptr points to a Derived object, it is actually


of Base type. So, it calls the member function of Base .
Difference between function overloading and
function overriding
1) Function Overloading happens in the same class when we declare same
functions with different arguments in the same class. Function Overriding is
happens in the child class when child class overrides parent class function.
2) In function overloading function signature should be different for all the
overloaded functions. In function overriding the signature of both the functions
(overriding function and overridden function) should be same.
3) Overloading happens at the compile time thats why it is also known as compile
time polymorphism while overriding happens at run time which is why it is known
as run time polymorphism.
4) In function overloading we can have any number of overloaded functions. In
function overriding we can have only one overriding function in the child class.

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. }
Test it Now

Output:

Bike is running safely

A real example of Java Method Overriding


Consider a scenario where Bank is a class that provides functionality to get the rate of
interest. However, the rate of interest varies according to banks. For example, SBI,
ICICI and AXIS banks could provide 8%, 7%, and 9% rate of interest.
Java method overriding is mostly used in Runtime Polymorphism which we will learn in next
pages.
1. //Java Program to demonstrate the real scenario of Java Method Overriding
2. //where three classes are overriding the method of a parent class.
3. //Creating a parent class.
4. class Bank{
5. int getRateOfInterest(){return 0;}
6. }
7. //Creating child classes.
8. class SBI extends Bank{
9. int getRateOfInterest(){return 8;}
10. }
11.
12. class ICICI extends Bank{
13. int getRateOfInterest(){return 7;}
14. }
15. class AXIS extends Bank{
16. int getRateOfInterest(){return 9;}
17. }
18. //Test class to create objects and call the methods
19. class Test2{
20. public static void main(String args[]){
21. SBI s=new SBI();
22. ICICI i=new ICICI();
23. AXIS a=new AXIS();
24. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
25. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
26. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
27. }
28. }
Test it Now

Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Can we override static method?
No, a static method cannot be overridden. It can be proved by runtime polymorphism,
so we will learn it later.

Why can we not override static method?


It is because the static method is bound with class whereas instance method is bound
with an object. Static belongs to the class area, and an instance belongs to the heap
area.

Can we override java main method?


No, because the main is a static method.

Super and this Keywords in Java


The super keyword in Java is a reference variable which is used to refer immediate
parent class object.

Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.

Usage of Java super Keyword


1. super can be used to refer immediate parent class instance variable.

2. super can be used to invoke immediate parent class method.

3. super() can be used to invoke immediate parent class constructor.


1) super is used to refer immediate parent class
instance variable.
We can use super keyword to access the data member or field of parent class. It is
used if parent class and child class have same fields.

1. class Animal{
2. String color="white";
3. }
4. class Dog extends Animal{
5. String color="black";
6. void printColor(){
7. System.out.println(color);//prints color of Dog class
8. System.out.println(super.color);//prints color of Animal class
9. }
10. }
11. class TestSuper1{
12. public static void main(String args[]){
13. Dog d=new Dog();
14. d.printColor();
15. }}
Test it Now

Output:

black
white

In the above example, Animal and Dog both classes have a common property color. If
we print color property, it will print the color of current class by default. To access the
parent property, we need to use super keyword.
2) super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class. In other words, it is used if method
is overridden.

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. void bark(){System.out.println("barking...");}
7. void work(){
8. super.eat();
9. bark();
10. }
11. }
12. class TestSuper2{
13. public static void main(String args[]){
14. Dog d=new Dog();
15. d.work();
16. }}
Test it Now

Output:

eating...
barking...

In the above example Animal and Dog both classes have eat() method if we call eat()
method from Dog class, it will call the eat() method of Dog class by default because
priority is given to local.

To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class constructor. Let's see a
simple example:
1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. super();
7. System.out.println("dog is created");
8. }
9. }
10. class TestSuper3{
11. public static void main(String args[]){
12. Dog d=new Dog();
13. }}
Test it Now

Output:

animal is created
dog is created

Note: super() is added in each class constructor automatically by compiler if there is no


super() or this().

super example: real use


Let's see the real use of super keyword. Here, Emp class inherits Person class so all the
properties of Person will be inherited to Emp by default. To initialize all the property, we
are using parent class constructor from child class. In such way, we are reusing the
parent class constructor.
1. class Person{
2. int id;
3. String name;
4. Person(int id,String name){
5. this.id=id;
6. this.name=name;
7. }
8. }
9. class Emp extends Person{
10. float salary;
11. Emp(int id,String name,float salary){
12. super(id,name);//reusing parent constructor
13. this.salary=salary;
14. }
15. void display(){System.out.println(id+" "+name+" "+salary);}
16. }
17. class TestSuper5{
18. public static void main(String[] args){
19. Emp e1=new Emp(1,"ankit",45000f);
20. e1.display();
21. }}
Test it Now

Output:

1 ankit 45000

this keyword in java


There can be a lot of usage of java this keyword. In java, this is a reference
variable that refers to the current object.
Usage of java this keyword
Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.

2. this can be used to invoke current class method (implicitly)

3. this() can be used to invoke current class constructor.

4. this can be passed as an argument in the method call.

5. this can be passed as argument in the constructor call.

6. this can be used to return the current class instance from the method.

Suggestion: If you are beginner to java, lookup only three usage of this keyword.
1) this: to refer current class instance variable

The this keyword can be used to refer current class instance variable. If there is ambiguity between
the instance variables and parameters, this keyword resolves the problem of ambiguity.

Understanding the problem without this keyword


Let's understand the problem if we don't use this keyword by the example given below:

1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. rollno=rollno;
7. name=name;
8. fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12. class TestThis1{
13. public static void main(String args[]){
14. Student s1=new Student(111,"ankit",5000f);
15. Student s2=new Student(112,"sumit",6000f);
16. s1.display();
17. s2.display();
18. }}
Test it Now

Output:

0 null 0.0
0 null 0.0

In the above example, parameters (formal arguments) and instance variables are same. So, we are
using this keyword to distinguish local variable and instance variable.

How to find Nth Highest Salary in SQL

Solution of the above problem by this keyword


1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. this.rollno=rollno;
7. this.name=name;
8. this.fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12.
13. class TestThis2{
14. public static void main(String args[]){
15. Student s1=new Student(111,"ankit",5000f);
16. Student s2=new Student(112,"sumit",6000f);
17. s1.display();
18. s2.display();
19. }}
Test it Now

Output:

111 ankit 5000


112 sumit 6000

If local variables(formal arguments) and instance variables are different, there is no need to use this
keyword like in the following program:

Program where this keyword is not required


1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int r,String n,float f){
6. rollno=r;
7. name=n;
8. fee=f;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12.
13. class TestThis3{
14. public static void main(String args[]){
15. Student s1=new Student(111,"ankit",5000f);
16. Student s2=new Student(112,"sumit",6000f);
17. s1.display();
18. s2.display();
19. }}
Test it Now

Output:

111 ankit 5000


112 sumit 6000

It is better approach to use meaningful names for variables. So we use same name for instance variables
and parameters in real time, and always use this keyword.

2) this: to invoke current class method

You may invoke the method of the current class by using the this keyword. If you don't use the this
keyword, compiler automatically adds this keyword while invoking the method. Let's see the
example

1. class A{
2. void m(){System.out.println("hello m");}
3. void n(){
4. System.out.println("hello n");
5. //m();//same as this.m()
6. this.m();
7. }
8. }
9. class TestThis4{
10. public static void main(String args[]){
11. A a=new A();
12. a.n();
13. }}
Test it Now

Output:

hello n
hello m

3) this() : to invoke current class constructor

The this() constructor call can be used to invoke the current class constructor. It is used to reuse
the constructor. In other words, it is used for constructor chaining.

Calling default constructor from parameterized constructor:

1. class A{
2. A(){System.out.println("hello a");}
3. A(int x){
4. this();
5. System.out.println(x);
6. }
7. }
8. class TestThis5{
9. public static void main(String args[]){
10. A a=new A(10);
11. }}
Test it Now

Output:

hello a
10

Calling parameterized constructor from default constructor:

1. class A{
2. A(){
3. this(5);
4. System.out.println("hello a");
5. }
6. A(int x){
7. System.out.println(x);
8. }
9. }
10. class TestThis6{
11. public static void main(String args[]){
12. A a=new A();
13. }}
Test it Now

Output:

5
hello a

Real usage of this() constructor call

The this() constructor call should be used to reuse the constructor from the constructor. It maintains
the chain between the constructors i.e. it is used for constructor chaining. Let's see the example
given below that displays the actual use of this keyword.

1. class Student{
2. int rollno;
3. String name,course;
4. float fee;
5. Student(int rollno,String name,String course){
6. this.rollno=rollno;
7. this.name=name;
8. this.course=course;
9. }
10. Student(int rollno,String name,String course,float fee){
11. this(rollno,name,course);//reusing constructor
12. this.fee=fee;
13. }
14. void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
15. }
16. class TestThis7{
17. public static void main(String args[]){
18. Student s1=new Student(111,"ankit","java");
19. Student s2=new Student(112,"sumit","java",6000f);
20. s1.display();
21. s2.display();
22. }}
Test it Now

Output:

111 ankit java null


112 sumit java 6000

Rule: Call to this() must be the first statement in constructor.


1. class Student{
2. int rollno;
3. String name,course;
4. float fee;
5. Student(int rollno,String name,String course){
6. this.rollno=rollno;
7. this.name=name;
8. this.course=course;
9. }
10. Student(int rollno,String name,String course,float fee){
11. this.fee=fee;
12. this(rollno,name,course);//C.T.Error
13. }
14. void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
15. }
16. class TestThis8{
17. public static void main(String args[]){
18. Student s1=new Student(111,"ankit","java");
19. Student s2=new Student(112,"sumit","java",6000f);
20. s1.display();
21. s2.display();
22. }}
Test it Now

Compile Time Error: Call to this must be first statement in constructor

4) this: to pass as an argument in the method

The this keyword can also be passed as an argument in the method. It is mainly used in the event
handling. Let's see the example:

1. class S2{
2. void m(S2 obj){
3. System.out.println("method is invoked");
4. }
5. void p(){
6. m(this);
7. }
8. public static void main(String args[]){
9. S2 s1 = new S2();
10. s1.p();
11. }
12. }
Test it Now

Output:

method is invoked

Application of this that can be passed as an argument:

In event handling (or) in a situation where we have to provide reference of a class to another one. It
is used to reuse one object in many methods.

5) this: to pass as argument in the constructor call

We can pass the this keyword in the constructor also. It is useful if we have to use one object in
multiple classes. Let's see the example:

1. class B{
2. A4 obj;
3. B(A4 obj){
4. this.obj=obj;
5. }
6. void display(){
7. System.out.println(obj.data);//using data member of A4 class
8. }
9. }
10.
11. class A4{
12. int data=10;
13. A4(){
14. B b=new B(this);
15. b.display();
16. }
17. public static void main(String args[]){
18. A4 a=new A4();
19. }
20. }
Test it Now

Output:10

6) this keyword can be used to return current class instance

We can return this keyword as an statement from the method. In such case, return type of the
method must be the class type (non-primitive). Let's see the example:

Syntax of this that can be returned as a statement

1. return_type method_name(){
2. return this;
3. }

Example of this keyword that you return as a statement from the


method

1. class A{
2. A getA(){
3. return this;
4. }
5. void msg(){System.out.println("Hello java");}
6. }
7. class Test1{
8. public static void main(String args[]){
9. new A().getA().msg();
10. }
11. }
Test it Now
Output:

Hello java

Proving this keyword

Let's prove that this keyword refers to the current class instance variable. In this program, we are
printing the reference variable and this, output of both variables are same.

1. class A5{
2. void m(){
3. System.out.println(this);//prints same reference ID
4. }
5. public static void main(String args[]){
6. A5 obj=new A5();
7. System.out.println(obj);//prints the reference ID
8. obj.m();
9. }
10. }
Test it Now

Output:

A5@22b3ea59
A5@22b3ea59

Final Keyword In Java


The final keyword in java is used to restrict the user. The java final keyword can be used
in many context. Final can be:

1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that have no value it
is called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in the
static block only. We will have detailed learning of these. Let's first learn the basics of
final keyword.

1) Java final variable


If you make any variable as final, you cannot change the value of final variable(It will be
constant).

Example of final variable


There is a final variable speedlimit, we are going to change the value of this variable, but
It can't be changed because final variable once assigned a value can never be changed.

1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
Test it Now

Output:Compile Time Error

2) Java final method


If you make any method as final, you cannot override it.

Example of final method

1. class Bike{
2. final void run(){System.out.println("running");}
3. }
4.
5. class Honda extends Bike{
6. void run(){System.out.println("running safely with 100kmph");}
7.
8. public static void main(String args[]){
9. Honda honda= new Honda();
10. honda.run();
11. }
12. }
Test it Now

Output:Compile Time Error

3) Java final class


If you make any class as final, you cannot extend it.

Example of final class

1. final class Bike{}


2. class Honda1 extends Bike{
3. void run(){System.out.println("running safely with 100kmph");}
4. public static void main(String args[]){
5. Honda1 honda= new Honda1();
6. honda.run();
7. }
8. }
Test it Now
Output:Compile Time Error

Q) Is final method inherited?


Ans) Yes, final method is inherited but you cannot override it. For Example:

1. class Bike{
2. final void run(){System.out.println("running...");}
3. }
4. class Honda2 extends Bike{
5. public static void main(String args[]){
6. new Honda2().run();
7. }
8. }
Test it Now
Output:running...

Q) What is blank or uninitialized final variable?


A final variable that is not initialized at the time of declaration is known as blank final
variable.

If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an
employee.

It can be initialized only in constructor.


Example of blank final variable

1. class Student{
2. int id;
3. String name;
4. final String PAN_CARD_NUMBER;
5. ...
6. }

Que) Can we initialize blank final variable?

Yes, but only in constructor. For example:

1. class Bike10{
2. final int speedlimit;//blank final variable
3.
4. Bike10(){
5. speedlimit=70;
6. System.out.println(speedlimit);
7. }
8.
9. public static void main(String args[]){
10. new Bike10();
11. }
12. }
Test it Now
Output: 70

static blank final variable


A static final variable that is not initialized at the time of declaration is known as static
blank final variable. It can be initialized only in static block.
Example of static blank final variable

1. class A{
2. static final int data;//static blank final variable
3. static{ data=50;}
4. public static void main(String args[]){
5. System.out.println(A.data);
6. }
7. }

Q) What is final parameter?

If you declare any parameter as final, you cannot change the value of it.

1. class Bike11{
2. int cube(final int n){
3. n=n+2;//can't be changed as n is final
4. n*n*n;
5. }
6. public static void main(String args[]){
7. Bike11 b=new Bike11();
8. b.cube(5);
9. }
10. }
Test it Now
Output: Compile Time Error

Q) Can we declare a constructor final?

No, because constructor is never inherited.


Static Binding and Dynamic Binding

Connecting a method call to the method body is known as binding.

There are two types of binding

1. Static Binding (also known as Early Binding).


2. Dynamic Binding (also known as Late Binding).

Understanding Type
Let's understand the type of instance.

1) variables have a type

Each variable has a type, it may be primitive and non-primitive.

1. int data=30;

Here data variable is a type of int.


2) References have a type
1. class Dog{
2. public static void main(String args[]){
3. Dog d1;//Here d1 is a type of Dog
4. }
5. }

3) Objects have a type


An object is an instance of particular java class, but it is also an instance of its superclass.

1. class Animal{}
2.
3. class Dog extends Animal{
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. }
7. }
Here d1 is an instance of Dog class, but it is also an instance of Animal.

static binding
When type of the object is determined at compiled time(by the compiler), it is known as
static binding.

If there is any private, final or static method in a class, there is static binding.

Example of static binding

1. class Dog{
2. private void eat(){System.out.println("dog is eating...");}
3.
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. d1.eat();
7. }
8. }

Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.

Example of dynamic binding

1. class Animal{
2. void eat(){System.out.println("animal is eating...");}
3. }
4.
5. class Dog extends Animal{
6. void eat(){System.out.println("dog is eating...");}
7.
8. public static void main(String args[]){
9. Animal a=new Dog();
10. a.eat();
11. }
12. }
Test it Now
Output:dog is eating...
In the above example object type cannot be determined by the compiler, because the instance of
Dog is also an instance of Animal.So compiler doesn't know its type, only its base type.
C++ Polymorphism
The term "Polymorphism" is the combination of "poly" + "morphs" which means many
forms. It is a greek word. In object-oriented programming, we use 3 main concepts:
inheritance, encapsulation, and polymorphism.

Real Life Example Of Polymorphism


Let's consider a real-life example of polymorphism. A lady behaves like a teacher in a
classroom, mother or daughter in a home and customer in a market. Here, a single
person is behaving differently according to the situations.

There are two types of polymorphism in C++:

o Compile time polymorphism: The overloaded functions are invoked by


matching the type and number of arguments. This information is available at the
compile time and, therefore, compiler selects the appropriate function at the
compile time. It is achieved by function overloading and operator overloading
which is also known as static binding or early binding. Now, let's consider the
case where function name and prototype is same.

1. class A // base class declaration.


2. {
3. int a;
4. public:
5. void display()
6. {
7. cout<< "Class A ";
8. }
9. };
10. class B : public A // derived class declaration.
11. {
12. int b;
13. public:
14. void display()
15. {
16. cout<<"Class B";
17. }
18. };

In the above case, the prototype of display() function is the same in both the base and
derived class. Therefore, the static binding cannot be applied. It would be great if the
appropriate function is selected at the run time. This is known as run time
polymorphism.

o Run time polymorphism: Run time polymorphism is achieved when the


object's method is invoked at the run time instead of compile time. It is achieved
by method overriding which is also known as dynamic binding or late binding.

Differences b/w compile time and run time


polymorphism.
Compile time polymorphism Run time polymorphism

The function to be invoked is known at the The function to be invoked is known at the
compile time. run time.
It is also known as overloading, early binding and It is also known as overriding, Dynamic
static binding. binding and late binding.

Overloading is a compile time polymorphism Overriding is a run time polymorphism where


where more than one method is having the same more than one method is having the same
name but with the different number of parameters name, number of parameters and the type of
or the type of the parameters. the parameters.

It is achieved by function overloading and It is achieved by virtual functions and


operator overloading. pointers.

It provides fast execution as it is known at the It provides slow execution as it is known at


compile time. the run time.

It is less flexible as mainly all the things execute It is more flexible as all the things execute at
at the compile time. the run time.

C++ Runtime Polymorphism Example


Let's see a simple example of run time polymorphism in C++.

// an example without the virtual keyword.

1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat(){
6. cout<<"Eating...";
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void eat()
13. { cout<<"Eating bread...";
14. }
15. };
16. int main(void) {
17. Dog d = Dog();
18. d.eat();
19. return 0;
20. }

Output:

Eating bread...

C++ Run time Polymorphism Example: By using two


derived class
Let's see another example of run time polymorphism in C++ where we are having two
derived classes.

// an example with virtual keyword.

1. #include <iostream>
2. using namespace std;
3. class Shape { // base class
4. public:
5. virtual void draw(){ // virtual function
6. cout<<"drawing..."<<endl;
7. }
8. };
9. class Rectangle: public Shape // inheriting Shape class.
10. {
11. public:
12. void draw()
13. {
14. cout<<"drawing rectangle..."<<endl;
15. }
16. };
17. class Circle: public Shape // inheriting Shape class.
18.
19. {
20. public:
21. void draw()
22. {
23. cout<<"drawing circle..."<<endl;
24. }
25. };
26. int main(void) {
27. Shape *s; // base class pointer.
28. Shape sh; // base class object.
29. Rectangle rec;
30. Circle cir;
31. s=&sh;
32. s->draw();
33. s=&rec;
34. s->draw();
35. s=?
36. s->draw();
37. }

Output:

drawing...
drawing rectangle...
drawing circle...

Runtime Polymorphism with Data Members


Runtime Polymorphism can be achieved by data members in C++. Let's see an example
where we are accessing the field by reference variable which refers to the instance of
derived class.

1. #include <iostream>
2. using namespace std;
3. class Animal { // base class declaration.
4. public:
5. string color = "Black";
6. };
7. class Dog: public Animal // inheriting Animal class.
8. {
9. public:
10. string color = "Grey";
11. };
12. int main(void) {
13. Animal d= Dog();
14. cout<<d.color;
15. }

Output:

Black
Virtual Destructor in C++
A destructor in C++ is a member function of a class used to free the space occupied by
or delete an object of the class that goes out of scope. A destructor has the same name
as the name of the constructor function in a class, but the destructor uses a
tilde (~) sign before its function name.

Virtual Destructor
A virtual destructor is used to free up the memory space allocated by the derived class
object or instance while deleting instances of the derived class using a base class pointer
object. A base or parent class destructor use the virtual keyword that ensures both base
class and the derived class destructor will be called at run time, but it called the derived
class first and then base class to release the space occupied by both destructors.

Why we use virtual destructor in C++?


When an object in the class goes out of scope or the execution of the main() function is
about to end, a destructor is automatically called into the program to free up the space
occupied by the class' destructor function. When a pointer object of the base class is
deleted that points to the derived class, only the parent class destructor is called due to
the early bind by the compiler. In this way, it skips calling the derived class' destructor,
which leads to memory leaks issue in the program. And when we use virtual keyword
preceded by the destructor tilde (~) sign inside the base class, it guarantees that first the
derived class' destructor is called. Then the base class' destructor is called to release the
space occupied by both destructors in the inheritance class.

Deleting a derived class object using a pointer of base class type that has a
non-virtual destructor results in undefined behavior. To correct this situation, the
base class should be defined with a virtual destructor. For example, following
program results in undefined behavior.

// CPP program without virtual destructor


// causing undefined behavior
#include<iostream>
Although the output of following program may be different on different
compilers, when compiled using Dev-CPP, it prints following:
Constructing base
Constructing derived
Destructing base
Making base class destructor virtual guarantees that the object of derived class
is destructed properly, i.e., both base class and derived class destructors are
called. For example,
Output:
Constructing base
Constructing derived
Destructing derived
Destructing base
As a guideline, any time you have a virtual function in a class, you should
immediately add a virtual destructor (even if it does nothing). This way, you
ensure against any surprises later.
Packages
Package in Java is a mechanism to encapsulate a group of classes, sub
packages and interfaces. Packages are used for:
 Preventing naming conflicts. For example there can be two classes with
name Employee in two packages, college.staff.cse.Employee and
college.staff.ee.Employee
 Making searching/locating and usage of classes, interfaces, enumerations
and annotations easier
 Providing controlled access: protected and default have package level
access control. A protected member is accessible by classes in the same
package and its subclasses. A default member (without any access
specifier) is accessible by classes in the same package only.
 Packages can be considered as data encapsulation (or data-hiding).

 How packages work?


Package names and directory structure are closely related. For example if a
package name is college.staff.cse, then there are three
directories, college, staff and cse such that cse is present in staff and staff is
present college. Also, the directory college is accessible
through CLASSPATH variable, i.e., path of parent directory of college is present
in CLASSPATH. The idea is to make sure that classes are easy to locate.
Package naming conventions : Packages are named in reverse order of domain
names, i.e., org.mvgr.oop. For example, in a college, the recommended
convention is college.tech.cse, college.tech.ee, college.art.history, etc.

Adding a class to a Package : We can add more classes to a created


package by using package name at the top of the program and saving it in the
package directory. We need a new java file to define a public class, otherwise
we can add the new class to an existing .java file and recompile it.

Subpackages: Packages that are inside another package are


the subpackages. These are not imported by default, they have to imported
explicitly. Also, members of a subpackage have no access privileges, i.e., they
are considered as different package for protected and default access specifiers.
Example :
import java.util.*;
util is a subpackage created inside java package.
Package in java can be categorized in two form, built-in package and user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Built-in Packages
These packages consist of a large number of classes which are a part of
Java API.Some of the commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines
primitive data types, math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like
Linked List, Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical
user interfaces (like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.

Here, we will have the detailed learning of creating and using user-defined packages.
Simple example of java package

The package keyword is used to create a package in java.

1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

1. javac -d directory javafilename

For example

1. javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file. You can use
any directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you
want to keep the package within the same directory, you can use . (dot).

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination.

The . represents the current folder.


How to access package from another package?
There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be

accessible but not subpackages.

The import keyword is used to make the classes and interface of another package

accessible to the current package.

Example of package that import the packagename.*


1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname


1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello

3) Using fully qualified name


If you use fully qualified name then only declared class of this package will be accessible.

Now there is no need to import. But you need to use fully qualified name every time

when you are accessing the class or interface.

It is generally used when two packages have same class name e.g. java.util and

java.sql packages contain Date class.


Example of package by import fully qualified name
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. obj.msg();
7. }
8. }
Output:Hello

Note: If you import a package, subpackages will not be imported.

If you import a package, all the classes and interface of that package will be imported excluding

the classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.

Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize

the package further.

Example of Subpackage

1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }

To Compile: javac -d . Simple.java


To Run: java com.javatpoint.core.Simple
Output:Hello subpackage

How to send the class file to another directory or drive?


There is a scenario, I want to put the class file of A.java source file in classes folder of c: drive.

For example:

1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
To Compile:

e:\sources> javac -d c:\classes Simple.java

To Run:

To run this program from e:\source directory, you need to set classpath of the directory

where the class file resides.

e:\sources> set classpath=c:\classes;.;

e:\sources> java mypack.Simple

Another way to run this program by -classpath switch of java:


The -classpath switch can be used with javac and java tool.

To run this program from e:\source directory, you can use -classpath switch of java that tells

where to look for class file. For example:

e:\sources> java -classpath c:\classes mypack.Simple

Output:Welcome to package

Ways to load the class files or jar files


There are two ways to load the class files temporary and permanent.

o Temporary
o By setting the classpath in the command prompt
o By -classpath switch
o Permanent
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying the jar file
in the jre/lib/ext folder.

Rule: There can be only one public class in a java source file and it must be saved by the public

class name.
1. //save as C.java otherwise Compile Time Error will be raised
2.
3. class A{}
4. class B{}
5. public class C{}

How to put two public classes in a package?


If you want to put two public classes in a package, have two java source files containing one public class, b
keep the package name same. For example:

1. //save as A.java
2.
3. package javatpoint;
4. public class A{}
1. //save as B.java
2.
3. package javatpoint;
4. public class B{}

You might also like