Inheritance4
Inheritance4
Inheritance in Java
In OOP, computer programs are designed in such a way where everything is an object that interact
with one another. Inheritance is one such concept where the properties of one class can be inherited
by the other. It helps to reuse the code and establish a relationship between different classes.
Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another. With the use of inheritance the information is made
manageable in a hierarchical order.
Inheritance is one of the cornerstones of object-oriented programming because it allows
the creation of hierarchical classifications.
Using inheritance, you can create a general class that defines traits common to a set of
related items. This class can then be inherited by other, more specific classes, each
adding those things that are unique to it.
The class which inherits the properties of other is known as subclass (derived class,
child class) and the class whose properties are inherited is known as superclass (base
class, parent class).
1 Collected by Bipin Timalsina
java programming
Inheritance Basics
To inherit a class, you simply incorporate the definition of one class into another by using
the extends keyword.
extends is the keyword used to inherit the properties of a class. Following is the syntax of
extends keyword.
Syntax
A major advantage of inheritance is that once you have created a superclass that defines
the attributes common to a set of objects, it can be used to create any number of more
specific subclasses. Each subclass can precisely tailor its own classification.
Example:
class Calculation {
int z;
public void addition(int x, int y) {
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
public void subtraction(int x, int y) {
z = x - y;
System.out.println("The difference between the given
numbers:"+z);
}
}
In the given program, when an object to My_Calculation class is created, a copy of the contents
of the superclass is made within it. That is why, using the object of the subclass you can access
the members of a superclass.
The Superclass reference variable can hold the subclass object, but using that variable you can
access only the members of the superclass, so to access the members of both classes it is
recommended to always create reference variable to the subclass.
A class member that has been declared as private will remain private to its class. It is not
accessible by any code outside its class, including subclasses
Using super
super is a keyword
Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the
keyword super. super has two general forms. The first calls the superclass’ constructor.
The second is used to access a member of the superclass that has been hidden by a
member of a subclass.
When a subclass calls super( ), it is calling the constructor of its immediate superclass.
Thus, super( ) always refers to the superclass immediately above the calling class. This is
true even in a multileveled hierarchy. Also, super( ) must always be the first statement
executed inside a subclass constructor.
Although the instance variable i in B hides the i in A, super allows access to the i defined
in the superclass. As you will see, super can also be used to call methods that are hidden
by a subclass.
Types of inheritances
class Car{
public Car()
{
System.out.println("Class Car");
}
public void vehicleType()
{
System.out.println("Vehicle Type: Car");
}
}
class Maruti extends Car{
public Maruti()
{
System.out.println("Class Maruti");
}
public void brand()
{
System.out.println("Brand: Maruti");
}
public void speed()
{
System.out.println("Max: 90Kmph");
}
}
public class Maruti800 extends Maruti{
public Maruti800()
{
System.out.println("Maruti Model: 800");
}
public void speed()
{
System.out.println("Max: 80Kmph");
}
public static void main(String args[])
{
Maruti800 obj=new Maruti800();
obj.vehicleType();
obj.brand();
obj.speed();
}
}
OUTPUT:
Polymorphism in Java
Polymorphism in java is a concept by which we can perform a single action by different ways.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in java: compile time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding
If two or more method in a class have same name but different parameters, it is known as
method overloading.
In Java, it is possible to define two or more methods within the same class that share the
same name, as long as their parameter declarations are different. When this is the case,
the methods are said to be overloaded, and the process is referred to as method
overloading
In order to overload a method, the parameter lists of the methods must differ in either of
these:
Number of parameters:
add(int a, int b)
add(int a, int b, int c)
Data type of parameters:
add(int x, int y)
add(int x, float y)
Sequence of data type of parameters
add(int p, float q)
add(float m , int n)
Overloading Constructors
In addition to overloading normal methods, you can also overload constructors
Constructor overloading is a concept of having more than one constructor with different
parameters list, in such a way so that each constructor performs a different task. They are
differentiated by the compiler by the number of parameters in the list and their types.
Constructor overloading is done to construct object in different ways.
In other words, If subclass provides the specific implementation of the method that has been
provided by one of its parent class, it is known as method overriding.
When show( ) is invoked on an object of type B, the version of show( ) defined within B is used.
That is, the version of show( ) inside B overrides the version declared in A.
If you wish to access the superclass version of an overridden method, you can do so by using
super.
When Parent class reference variable refers to Child class object, it is known
as Upcasting
Through the dual mechanisms of inheritance and run-time polymorphism, it is possible to define
one consistent interface that is used by several different, yet related, types of objects. In this case,
if an object is derived from Figure, then its area can be obtained by calling area( ). The interface
to this operation is the same no matter what type of figure is being used.
In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable.
Upcasting: When reference variable of Parent class refers to the object of Child class, it is known
as upcasting.
Association of method call to the method body is known as binding. There are two types of
binding: Static Binding that happens at compile time and Dynamic Binding that happens at
runtime.
The binding which can be resolved at compile time by compiler is known as static or early
binding. The binding of static, private and final methods is compile-time. Why? The
reason is that these method cannot be overridden and the type of the class is determined at
the compile time.
class Human{
public static void walk()
{
System.out.println("Human walks");
}
}
class Boy extends Human{
public static void walk(){
System.out.println("Boy walks");
}
public static void main( String args[]) {
/* Reference is of Human type and object is
* Boy type
*/
Human obj = new Boy();
/* Reference is of HUman type and object is
* of Human type.
*/
Human obj2 = new Human();
obj.walk();
obj2.walk();
}
}
When compiler is not able to resolve the call/binding at compile time, such binding is
known as Dynamic or late Binding. Method Overriding is a perfect example of dynamic
binding as in overriding both parent and child classes have same method and in this case
the type of the object determines which method is to be executed. The type of object is
determined at the run time so this is known as dynamic binding.
class Human{
//Overridden Method
public void walk()
{
System.out.println("Human walks");
}
}
class Demo extends Human{
//Overriding Method
public void walk(){
System.out.println("Boy walks");
}
public static void main( String args[]) {
/* Reference is of Human type and object is
* Boy type
*/
Human obj = new Demo();
/* Reference is of HUman type and object is
* of Human type.
*/
Human obj2 = new Human();
obj.walk();
obj2.walk();
}
}
As you can see that the output is different than what we saw in the static binding example, because
in this case while creation of object obj the type of the object is determined as a Boy type so method
of Boy class is called. Remember the type of the object is determined at the runtime.
Let’s discuss the difference between static and dynamic binding in Java.
Encapsulation in Java
Encapsulation is a mechanism where you bind your data and code together as a single unit. It also
means to hide your data in order to make it safe from any modification. What does this mean? The
best way to understand encapsulation is to look at the example of a medical capsule, where the
drug is always safe inside the capsule. Similarly, through encapsulation the methods and variables
of a class are well hidden and safe.
In encapsulation, the variables of a class will be hidden from other classes, and can be accessed
only through the methods of their current class. Therefore, it is also known as data hiding.
Example
return age;
return name;
return idNum;
age = newAge;
name = newName;
idNum = newId;
The public setXXX() and getXXX() methods are the access points of the instance variables of the
EncapTest class. Normally, these methods are referred as getters and setters. Therefore, any class
that wants to access the variables should access them through these getters and setters.
The variables of the EncapTest class can be accessed using the following program –
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
Output
Benefits of Encapsulation
The fields of a class can be made read-only or write-only.
A class can have total control over what is stored in its fields.
Abstraction in Java
As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example,
when you consider the case of e-mail, complex details such as what happens as soon as you send
an e-mail, the protocol your e-mail server uses are hidden from the user. Therefore, to send an e-
mail you just need to type the content, mention the address of the receiver, and click send.
Abstract Classes
There are situations in which you will want to define a superclass that declares the
structure of a given abstraction without providing a complete implementation of every
method.
That is, sometimes you will want to create a superclass that only defines a generalized
form that will be shared by all of its subclasses, leaving it to each subclass to fill in the
details. Such a class determines the nature of the methods that the subclasses must
implement.
One way this situation can occur is when a superclass is unable to create a meaningful
implementation for a method. This is the case with the class Figure used in the preceding
example. The definition of area( ) is simply a placeholder. It will not compute and display
the area of any type of object.
As you will see as you create your own class libraries, it is not uncommon for a method
to have no meaningful definition in the context of its superclass. You can handle this
situation two ways. One way, as shown in the previous example, is to simply have it
report a warning message. While this approach can be useful in certain situations—such
as debugging—it is not usually appropriate. You may have methods that must be
overridden by the subclass in order for the subclass to have any meaning. Consider the
class Triangle. It has no meaning if area( ) is not defined. In this case, you want some
way to ensure that a subclass does, indeed, override all necessary methods. Java’s
solution to this problem is the abstract method.
You can require that certain methods be overridden by subclasses by specifying the
abstract type modifier. These methods are sometimes referred to as subclasser
responsibility because they have no implementation specified in the superclass. Thus, a
subclass must override them—it cannot simply use the version defined in the superclass.
Abstract Method??
Example:
abstract class Shape{
void meth(){
System.out.println("I am from normal method");
}
abstract void draw();
}
class Rectangle extends Shape{
void draw(){
System.out.println("drawing rectangle");}
}
class Circle extends Shape{
void draw(){
System.out.println("drawing circle");
}
}
class TestAbstraction{
public static void main(String args[]){
Shape s=new Circle();
s.draw();
}
}
Let’s say we have a class Animal that has a method sound() and the
subclasses(see inheritance) of it like Dog, Lion, Horse, Cat etc. Since the animal sound
differs from one animal to another, there is no point to implement this method in parent
class. This is because every child class must override this method to give its own
implementation details, like Lion class will say “Roar” in this method and Dog class will
say “Woof”.
So when we know that all the animal child classes will and should override this method,
then there is no point to implement this method in parent class. Thus, making this method
abstract would be the good choice as by making this method abstract we force all the sub
classes to implement this method( otherwise you will get compilation error), also we need
not to give any implementation to this method in parent class.
Since the Animal class has an abstract method, you must need to declare this class abstract.
Now each animal must have a sound, by making this method abstract we made it
compulsory to the child class to give implementation details to this method. This way we
ensures that every animal has a sound.
Because these classes are incomplete, they have abstract methods that have no body. So if java
allows you to create object of this class then if someone calls the abstract method using that
object then what would happen? There would be no actual implementation of the method to
invoke.
Also because an object is concrete. An abstract class is like a template, so you have to extend it
and build on it before you can use it.
An abstract class has no use until unless it is extended by some other class.
If you declare an abstract method in a class then you must declare the class abstract as well.
You can’t have abstract method in a concrete class. It’s vice versa is not always true: If a
class is not having any abstract method then also it can be marked as abstract.
Abstract class can have non-abstract method (concrete) as well.
Interface in Java
An interface is a reference type in Java. It is similar to class
An interface in java is a blueprint of a class. It has static constants and abstract methods.
Using the keyword interface, you can fully abstract a class’ interface from its
implementation. That is, using interface, you can specify what a class must do, but not
how it does it.
Interfaces specify what a class must do and not how.
Interfaces are syntactically similar to classes, but they lack instance variables, and, as a
general rule, their methods are declared without any body. In practice, this means that
you can define interfaces that don’t make assumptions about how they are implemented.
Once it is defined, any number of classes can implement an interface. Also, one class can
implement any number of interfaces.
Writing an interface is similar to writing a class. But a class describes the attributes and
behaviors of an object. And an interface contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface
need to be defined in the class.
Syntax:
[modifiers] interface InterfaceName {
// declaring methods
[public abstract] returnType methodName1(arguments);
// defining constants
[public static final] type fieldName = value;
}
The access level for the entire interface is usually public. It may be omitted, in which
case the interface is only available to other classes in the same package (i.e. default
access).Note, for the sake of completeness, and there are situations where the interface
definition could be protected or private; these involve what are called inner classes.
Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface. To
implement an interface, include the implements clause in a class definition, and then
create the methods required by the interface.
When a class implements an interface, you can think of the class as signing a contract,
agreeing to perform the specific behaviors of the interface. If a class does not perform all
the behaviors of the interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface
Syntax:
[modifiers] class ClassName implements InterfaceName {
//any desired fields
If a class implements more than one interface, the interfaces are separated with a comma.
If a class Tyre is implementing two interfaces Moveable and Rollable then
class Tyre implements Moveable, Rollable
{
. . . .
}
It is both permissible and common for classes that implement interfaces to define
additional members of their own.
Another Example:
interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class NMB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}
}
Extending Interfaces
One interface can inherit another by use of the keyword extends. The syntax is the same as for
inheriting classes. When a class implements an interface that inherits another interface, it must
provide implementations for all methods required by the interface inheritance chain.
Following is an example:
The extends keyword is used once, and the parent interfaces are declared in a comma-separated
list.
Multiple inheritance is not supported through class in java, but it can be achieved using
interfaces
interface Printable{
void print();
}
interface Showable{
void show();
}
class Test implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
Without bothering about the implementation part, we can achieve the security of
implementation
In java, multiple inheritance is not allowed, however you can use interface to make use
of it as you can implement more than one interface.
1. Type of methods: Interface can have only abstract methods. Abstract class can have
abstract and non-abstract methods. From Java 8, it can have default and static methods also.
2. Final Variables: Variables declared in a Java interface are by default final. An abstract
class may contain non-final variables.
3. Type of variables: Abstract class can have final, non-final, static and non-static variables.
Interface has only static and final variables.
4. Implementation: Abstract class can provide the implementation of interface. Interface
can’t provide the implementation of abstract class.
5. Inheritance vs Abstraction: A Java interface can be implemented using keyword
“implements” and abstract class can be extended using keyword “extends”.
6. Multiple implementation: An interface can extend another Java interface only, an abstract
class can extend another Java class and implement multiple Java interfaces.
7. Accessibility of Data Members: Members of a Java interface are public by default. A Java
abstract class can have class members like private, protected, etc.
If we make any variable as final, we cannot change the value of final variable
(It will be constant) [final variable once assigned a value can never be changed.]
If we make any method as final, we cannot override it.
If we make any class as final, we cannot extend it ( i.e. we cannot create subclass)
obj.run();
}
}//end of class