11.inheritance and Polymorphism
11.inheritance and Polymorphism
Inheritance
• 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.
Terms used in Inheritance
Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
class Subclass-name extends Superclass-name
{
//methods and fields
}
{ System.out.println(s.area());
Hello
More points on Downcasting
1st Scenario: 3rd Scenario:
class ABC{} class ABC{}
class PQR extends ABC{ class PQR extends ABC{
public static void main(String args[]){
public static void main(String args[]){
PQR obj=new ABC();//Compile time error
ABC obj1=new PQR();
}
PQR obj2=(PQR)obj1;
}
2nd Scenario: }
class ABC{} }
class PQR extends ABC{ In third scenario, there will be no error
public static void main(String args[]){
ABC obj1=new ABC();
PQR obj2=(PQR) obj1;//Runtime error[ClassCastException]
}
}
Instanceof operator
• The java instanceof operator is used to test whether the object is an
instance of the specified type (class or subclass or interface).
class ABC{}
class PQR extends ABC{
public static void main(String args[]){
PQR obj=new PQR();
System.out.println(obj instanceof ABC);//true
}
}
Example 3-instanceof can help in downcasting
class ABC{}
class PQR extends ABC{
public static void main(String args[]){
ABC obj1=new PQR();
if(obj1 instanceof PQR) //It will return true
{
PQR obj2=(PQR)obj1;
System.out.println("Downcasting done");
}
else
{
System.out.println("Downcasting not possible");
}
}
}
Access Modifiers/or levels in Java
• Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
• Default: The access level of a default modifier is only within the package.
It cannot be accessed from outside the package. If you do not specify any
access level, it will be the default.
• Protected: The access level of a protected modifier is within the package
and outside the package through child class. If you do not make the child
class, it cannot be accessed from outside the package.
• Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package and
outside the package.
Access modifiers-Summary
Q1