Anda di halaman 1dari 5

Inheritance in Java

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of
parent object.
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 parent class, and you can
add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Why use inheritance in java
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
Syntax of Java Inheritance
1. class Subclass-name extends Superclass-name
2. {
3.
//methods and fields
4. }
extends Keyword
extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends
keyword.
class Super{
.....
.....
}
class Sub extends Super{
.....
.....
}
The extends keyword indicates that you are making a new class that derives from an existing class.
In the terminology of Java, a class that is inherited is called a super class. The new class is called a
subclass.
Understanding the simple example of inheritance

As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
Relationship between 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. }
Test it Now
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.

Note: Multiple inheritance is not supported in java through class.


When a class extends multiple classes i.e. known as multiple inheritance. For Example:

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 same method and you call it from child class object, there will be ambiguity to call 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 now.
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. }
Test it Now
Compile Time Error
Simple example of Inheritance
class Parent
{
public void p1()
{
System.out.println("Parent method");
}
}
public class Child extends Parent {
public void c1()
{
System.out.println("Child method");
}
public static void main(String[] args)
{

Child cobj = new Child();


cobj.c1(); //method of Child class
cobj.p1(); //method of Parent class
}
}
Output
Child method
Parent method
Another example of Inheritance
class Vehicle
{
String vehicleType;
}
public class Car extends Vehicle {
String modelType;
public void showDetail()
{
vehicleType = "Car";
//accessing Vehicle class member
modelType = "sports";
System.out.println(modelType+" "+vehicleType);
}
public static void main(String[] args)
{
Car car =new Car();
car.showDetail();
}
}
Output
sports Car
----------------------------------------------------------------------------------------------------------------------------------------// A class to display the attributes of the vehicle
class Vehicle {
String color;
int speed;
int size;
void attributes() {
System.out.println("Color : " + color);
System.out.println("Speed : " + speed);
System.out.println("Size : " + size);
}
}
// A subclass which extends for vehicle
class Car extends Vehicle {
int CC;
int gears;
void attributescar() {
// The subclass refers to the members of the superclass
System.out.println("Color of Car : " + color);
System.out.println("Speed of Car : " + speed);
System.out.println("Size of Car : " + size);
System.out.println("CC of Car : " + CC);
System.out.println("No of gears of Car : " + gears);
}
}
public class Test {
public static void main(String args[]) {
Car b1 = new Car();
b1.color = "Blue";
b1.speed = 200 ;
b1.size = 22;
b1.CC = 1000;
b1.gears = 5;
b1.attributescar();
}

}
The output is
Color of Car : Blue
Speed of Car : 200
Size of Car : 22
CC of Car : 1000
No of gears of Car : 5
Visibility Control
It is possible to inherit all the members of a class by a subclass using the keyword extends. The
variables and methods of a class are visible everywhere in the program. However, it may be
necessary in some situations we may want them to be not accessible outside. We can achieve this in
Java by applying visibility modifiers to instance variables and methods. The visibility modifiers are
also known as access modifiers. Access modifiers determine the accessibility of the members of a
class.
Java provides three types of visibility modifiers: public, private and protected. They provide
different levels of protection as described below.
Public Access: Any variable or method is visible to the entire class in which it is defined. But, to
make a member accessible outside with objects, we simply declare the variable or method as
public. A variable or method declared as public has the widest possible visibility and accessible
everywhere.
Friendly Access (Default): When no access modifier is specified, the member defaults to a limited
version of public accessibility known as "friendly" level of access. The difference between the
"public" access and the "friendly" access is that the public modifier makes fields visible in all
classes, regardless of their packages while the friendly access makes fields visible only in the same
package, but not in other packages.
Protected Access: The visibility level of a "protected" field lies in between the public access and
friendly access. That is, the protected modifier makes the fields visible not only to all classes and
subclasses in the same package but also to subclasses in other packages
Private Access: private fields have the highest degree of protection. They are accessible only with
their own class. They cannot be inherited by subclasses and therefore not accessible in subclasses.
In the case of overriding public methods cannot be redefined as private type.
Private protected Access: A field can be declared with two keywords private and protected
together. This gives a visibility level in between the "protected" access and "private" access. This
modifier makes the fields visible in all subclasses regardless of what package they are in.
Remember, these fields are not accessible by other classes in the same package.
Access Control and Inheritance:
The following rules for inherited methods are enforced:

Methods declared public in a superclass also must be public in all subclasses.

Methods declared protected in a superclass must either be protected or public in subclasses; they
cannot be private.

Methods declared without access control (no modifier was used) can be declared more private in
subclasses.

Methods declared private are not inherited at all, so there is no rule for them.

Understanding all java access modifiers


Let's understand the access modifiers by a simple table.

Access Modifier
Private
Default
Protected
Public

within class
Y
Y
Y
Y

within package
N
Y
Y
Y

outside package by subclass only


N
N
Y
Y

outside package
N
N
N
Y

Anda mungkin juga menyukai