Unit - 3
Unit - 3
Unit - 3
UNIT – III
SL No. Index
1 Relationships- Inheritance: purpose and its types
2 IS-A Relationships
3 Association
4 Aggregation
5 Interfaces
6 Abstract classes
Inheritance
The capability of a class to derive properties and characteristics from another class is called
Inheritance. Inheritance is one of the most important features of Object-Oriented
Programming.
Inheritance is a feature or a process in which, new classes are created from the existing
classes. The new class created is called “derived class” or “child class” and the existing class
is known as the “base class” or “parent class”. The derived class now is said to be inherited
from the base class.
When we say derived class inherits the base class, it means, the derived class inherits all the
properties of the base class, without changing the properties of base class and may add new
features to its own. These new features in the derived class will not affect the base class.
Derived Class: The class that inherits properties from another class is called Subclass or
Derived Class.
Base Class: The class whose properties are inherited by a subclass is called Base Class or
Superclass.
Advantage of C++ Inheritance
Code reusability: Reuse the members such as variables, methods defined in your parent
class. There is no need to define the member again so less code is required in the class.
Types of Inheritance
Five types of inheritance:
Single inheritance
Multiple inheritance
Hierarchical inheritance
Multilevel inheritance
Hybrid inheritance
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. 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.
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:
In C++, the default mode of visibility is private.
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. The example of
single level inheritance which inherits the base class variables only.
#include <iostream>
using namespace std;
class Account {
public:
float salary = 60000;
};
class Programmer: public Account {
public:
float bonus = 5000;
};
int main()
{
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
return 0;
}
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
Another example of inheritance in C++ which inherits methods only.
#include <iostream>
using namespace std;
class Vehicle {
public:
void engine() {
cout<<"Engine started"<<endl;
}
};
class Car: public Vehicle
{
public:
void car_break(){
cout<<"Breaking";
}
};
int main() {
Vehicle d1;
d1.engine();
d1.car_break);
return 0;
}
Output:
Engine Started...
Breaking...
Let's see a simple example.
#include <iostream>
using namespace std;
class A
{
int a = 4;
int b = 5;
public:
int mul()
{
int c = a*b;
return c;
}
};
class B : private A
{
public:
void display()
{
int result = mul();
std::cout <<"Multiplication of a and b is : "<<result<< std::endl;
}
};
int main()
{
B b;
b.display();
return 0;
}
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 who 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:
Public: When the member is declared as public, it is accessible to all the functions of the
program.
Private: When the member is declared as private, it is accessible within the class only.
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
Multilevel Inheritance
Multilevel inheritance is a process of deriving a class from another derived class.
Association is a relationship between two classes where one class uses another.
It is inflexible in nature
It means there is almost always a link between objects
It is represented by a “has a” relationship.
Line segment is used between the components or the class.
In one-to-one relationships, an entity of one database is uniquely related to an entity of
another database. For example, if we consider customer table and address table related to
customer table, then customer table and address table are said to be in one-to-one relationship
with each other.
One-to-many and many-to-one relationships – In this kind of relationships, one entity of a
database may be related to one or more entities of another database and vice versa. For
example, if we consider the same customer table as in Table 2.1 and assume the online
transaction on any e-commerce website, then we may consider the facts that
One customer can make many orders.
More than one item can be made in one order.
Now considering these two situations, we will have one-to-many relationships.
Aggregation describes a special type of an association which specifies a whole and part
relationship.
It in flexible in nature
Special kind of association where there is whole-part relation between two objects.
It is represented by a “has a”+ “whole-part” relationship.
Diamond shape structure is used next to the assembly class.
Association is a relation between two separate classes which establishes through their
Objects. Association can be one-to-one, one-to-many, many-to-one, many-to-many. In
Object-Oriented programming, an Object communicates to another object to use functionality
and services provided by that object. Composition and Aggregation are the two forms of
association.
It is a special form of Association where:
It represents Has-A’s relationship.
It is a unidirectional association i.e. a one-way relationship. For example, a department
can have students but vice versa is not possible and thus unidirectional in nature.
In Aggregation, both entries can survive individually which means ending one entity
will not affect the other entity.
Aggregation
It represents a Has-A relationship. In the above example: Student Has-A name. Student Has-
A ID. Student Has-A Dept. Department Has-A Students as depicted from the below media.
Composition
Composition
Composition is a restricted form of Aggregation in which two entities are highly dependent
on each other.
It represents part-of relationship.
In composition, both entities are dependent on each other.
When there is a composition between two entities, the composed object cannot exist
without the other entity.
Aggregation vs. Composition
Dependency: Aggregation implies a relationship where the child can exist independently of
the parent. For example, Bank and Employee, delete the Bank and the Employee still exist.
whereas Composition implies a relationship where the child cannot exist independent of the
parent. Example: Human and heart, heart don’t exist separate to a Human
Type of Relationship: Aggregation relation is “has-a” and composition is “part-of”
relation.
Type of association: Composition is a strong Association whereas Aggregation is a weak
Association.
Interface
Here in C++, No concept of Interface. We study interface through java. Interface in Java is
a blueprint of a class. It has static constants and abstract methods. The interface in Java is a
mechanism to achieve abstraction. There can be only abstract methods in the Java interface,
not method body. It is used to achieve abstraction and multiple inheritances in Java. You can
say that interfaces can have abstract methods and variables. It cannot have a method body.
Java Interface also represents the IS-A relationship. It cannot be instantiated just like the
abstract class. Since Java 8, we can have default and static methods in an interface. Since
Java 9, we can have private methods in an interface. There are mainly three reasons to use
interface. They are given below.
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritances.
It can be used to achieve loose coupling.
Normal or Simple method is called concrete method.
In interface we declare only Abstract method in interface.
It is used to achieve abstraction.
it supports multiple Inheritance.
Interface support loose coupling.
Example :
interface Interface_Name
{
Methods
Fields
}
Only abstract method not concrete method declare in Interface.
All method are public declared externally. If not declare public, Compiler automatically
declare public internally.
By default, method and fields are public, static, final declaration.
Note : In JDK version 1.8, JDK 1.9 and Modern Java JDK, we declare concrete method in
Interface, but access specifier of concrete method declared in Interface must be default
Access. But In case Abstract method, access specifier is must be public, static and final
externally declared by programmer. And internally declared by java compiler. In JDK 1.9 we
also create private concrete method in Interface.
Example:
interface I1
{
void show();
}
class Test implements I1
{
public void show();
{
System.out.println(“1”);
}
public static void main(String[] args)
{
Test t = new Test();
t.show();
}
}
In Interface we create method, it is not mandatory to insert abstract keyword into method.
All variables is in Interface is public static final type.
Interface I1
{
void show();
}
interface I2
{
void display();
}
class Test implements I1, I2
{
public void show()
{
System.out.println(“1”);
}
public void display()
{
System.out.println(“2”);
}
public static void main(String[] args)
{
Test t = new Test();
t1.show();
t1.display();
}
}
Interface Implementation
Think of an interface as a 100% abstract class. Like an abstract class an interface defines
abstract method that take the form.
abstract void bounce()
An abstract class can define both abstract and non abstract methods, but an interface can have
only abstract methods.
Interface Rules
All interface methods are implicitly public and abstract.
Interface methods must not be static.
We can create class in interface using jdk 1.8 or later.
We can create concrete method in interface but declared concrete method must be static.
Otherwise give error without static.
We can not use static keyword with abstract method.
Because interface methods are abstract, they cannot be marked as final, native, strictfp, or
synchronized.
You do not need to actually type the public or an abstract modifiers in the method
declaration, The method still always public and abstract.
Variable deceleration in interface must be initialized.
All variable defined in interface must be public, static and final, in other words the
interface declares only constants not instance variable.
An interface can extend one or more interfaces.
An interface extends another interface.
A Class implements Interface.
An interface cannot implements another interface or class.
An interface must be declared with the keyword interface.
Interface type can be used polymorphically.
The following is a legal interface deceleration:
public abstract interface Rollable()
Interface are implicitly abstract whether you type or not.
public abstract interface Rollable()
public interface Rollable()
The public modifier is required if you want the interface to have public rather than
default. If declared public its must me declared its own separate file.
Interface methods declared with any combination of public, abstract or no modifiers. For
example, the following five method declarations. If declared within on interface are legal and
identical
void bounce(); // OK
public void bounce(); //OK
abstract void bounce(); //OK
public abstract void bounce(); //OK
abstract public void bounce(); //OK
The following interface method declaration won’t compile:
final void bounce(); //final and abstract can never be used
static void bounce(); //interfaces define instance methods
private void bounce(); //interface methods are always public
protected void bounce(); // (same as above)
synchronized void bounce(); //can’t mix synchronized and abstract
native void bounce(); // can’t mix abstract and native
strictfp void bounce(); // can not mix abstract and strictfp
Declaring Interface Constants
Any class implementing the interface will have access to the same constants.
public final static int LOW_BOUNCE = 4;
public final static int LOW_BOUNCE = 3;
if a method takes the int values,
public void animateIt(int gravity, int bounceFactor)
{
}
Then the code that calls animateIt() can substitute the constants, whenever the int values are
expected as follows:
animator.animateIt(LOW_GRAVITY, HIGH_BOUNCE);
Any class that implements the interface has direct access to the constants, just as if the class
had inherited them. A few rules for interface constants :
public
static
final
Interface constants are no different from any other publicly accessible constants so they
obviously must be declared public, static and final.
Any variable defined in an interface must be and implicitly is a public constant.
You can’t change the value of constant once the value is assigned to the constants. This
assignment happens in the interface itself (where the constant is declared). So the
implementing class can access it an use it but as a read-only value.
Look interface definition that defines constants , but without explicitly using the required
modifiers. For example the following are all identical:
public int x = 1; //looks non static and non final, but isn’t
int x = 1; // looks default non final, and non-static but isn’t.
static int x = 1; //doesn't show final or public
final int x = 1 //doesn’t show static or publicly
public static int x = 1; // doesn’t show final
public final int x = 1; //Doesn’t show static
static final int x = 1; //doesn’t show public
public static final int x = 1; // exactly what you get implicitly.
Any combination of the required (but implicit) modifiers is legal as is using no modifiers at
all.
Implementing an Interface
Implementing classes must adhere to the same rule for method implementing as a class
extending an abstract class. In order to be legal implementation class, a non abstract
implementation class must do the following:
Provide concrete (non abstract) implementations for all method form the declared
interface.
Follow all the rules for legal overrides
Declare no checked exceptions on implementations methods other than those declared by
the interface method, or subclass of those declared by the interface method.
Maintaining the signature of the interface method, and maintain the same return type( but
does not have to declare the exceptions declared in the interface method declaration).
A class can extends more than one interface using extend keyword. And Interface is also
extend to another interfaces using the extend keyword. In the case of class use implement
keyword .
public class Ball implements Bounceable, Serializable, Runnable{…}
Interface C extends A, B // Legal
You can extend only one class, but implement many. But remember that sub-classing defines
who and what you are, where implementing defines a role you can play or a hat you can
wear, despite how different you might be from some other class implementing the same
interface. An interface cal itself extend another interface, but never implement anything.
The following code is perfectly legal:
public interface Bounceable extends Movable { }
The first concrete(no abstract) implementations class of Bounceable must implement all
the methods of Bounceable, plus all the methods of Movable.
An interface can extends more than one interface.
A class is not allowed to extend multiple classes in java. An interface however is free to
extend multiple interfaces. This is legal to declare interface into public access class.