Java Unit 2
Java Unit 2
Java Unit 2
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 asa parent-
child relationship.
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.
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.
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.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String
args[]){Programmer p=new
Programmer();
}
}
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own classas 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.
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 thesingle inheritance.
File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String
d.bark();
d.eat();
}}
Output:
barking...
eating...
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String
Output:
meowing...
eating...
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 inheritsA 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.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
Whenever you create the instance of subclass, an instance of parent class iscreated
implicitly which is referred by super reference variable.
Usage of Java super Keyword
We can use super keyword to access the data member or field of parentclass. It is
used if parent class and child class have same fields.
class Animal{
String color="white";
}
class Dog extends
Animal{String
color="black";
void printColor()
{
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String
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.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating
bread...");} void
bark(){System.out.println("barking...");} void
work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String
d.work();
}}
Output:
eating...
barking...
In the above example Animal and Dog both classes have eat() method if wecall eat()
method from Dog class, it will call the eat() method of Dog class by default because
priority is given to local.
class Animal{
Animal(){System.out.println("animal is
created");}
}
class Dog extends
Animal{Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String
}}
Output:
animal is created
dog is created
Method Overriding
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.
In this page, we will learn about Java objects and classes. In object-oriented programming technique, we
design a program using objects and classes.
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity only.
An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.
Object Definitions:
A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created. It is a logical entity. It can't be physical.
o Fields
o Methods
o Constructors
o Blocks
File: Student.java
System.out.println(s1.name);
}
}
Output:
0
Null
Polymorphism in Java
In this example, we are creating two classes Bike and Splendor. Splendor class
extends Bike class and overrides its run() method. We are calling the run method by
the reference variable of Parent class. Since it refers to the subclass object and subclass
method overrides the Parent class method, the subclass method is invoked at runtime.
class Bike
{
void run()
{
System.out.println("running");
}
}
class Splendor extends Bike
{
void run()
{
System.out.println("running safely with 60km");
}
Compile time polymorphism in Java is also known as early binding or static polymorphism. The binding
is performed during compilation time and hence the name compile-time polymorphism. Binding refers to
connecting the function call to the function body. It is achieved by overloading methods, operator overloading,
and by changing the signature of the function.
Example
Connecting a method call to the method body is known as binding.There are two
types of binding
static binding
When type of the object is determined at compiled time(by the compiler), itis known
as static binding.
If there is any private, final or static method in a class, there is static binding.
class Dog{
private void eat(){System.out.println("dog is eating...");}
d1.eat();
}
}
Dynamic binding
When type of the object is determined at run-time, it is known as dynamicbinding.
class Animal
{
void eat()
{
System.out.println("animal is eating...");
}
}
Type Casting in Java Converting a lower data type into a higher one is called widening type
casting. It is also known as implicit conversion or casting down. It is done
In Java, type casting is a method or process that converts a data type into automatically. It is safe because there is no chance to lose data. It takes
another data type in both ways manually and automatically. The automatic place when:
conversion is done by the compiler and manual conversion performed by the
programmer. In this section, we will discuss type casting and its types with o Both
oth data types must be compatible with each other.
proper examples.
o The target type must be larger than the source type.
byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean
is not done automatically.
ally. Also, the char and Boolean data types are not
compatible with each other. Let's see an example.
WideningTypeCastingExample.java
Let's see the simple example of instance operator where it tests the current Ways to achieve Abstraction
class.
There are two ways to achieve abstraction in java
class Simple1{
public static void main(String args[]){ 1. Abstract class (0 to 100%)
Simple1 s=new Simple1(); 2. Interface (100%)
System.out.println(s instanceof Simple1);//true
}
} Abstract class in Java
Before learning the Java abstract class, let's understand the abstraction in o It cannot be instantiated.
Java first. o It can have constructors and static methods also.
Abstraction in Java o It can have final methods which will force the subclass not to change
the body of the method.
Abstraction is a process of hiding the implementation details and showing
only functionality to the user.
Another way, it shows only essential things to the user and hides the internal
details, for example, sending SMS where you type the text and send the
message. You don't know the internal processing about the message
delivery.
}
Example of abstract class Output:
running safely
abstract class A{}
Interface in Java
Abstract Method in Java An interface in Java is a blueprint of a class. It has static constants and
abstract methods.
A method which is declared as abstract and does not have implementation is
known as an abstract method. 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
Example of abstract method achieve abstraction and multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and
abstract void printStatus();//no method body and abstract
variables. It cannot have a method body.
// declare constant fields Package in java can be categorized in two form, built-in package and user-
defined package.
// declare methods that abstract
// by default. There are many built-in packages such as java, lang, awt, javax, swing, net,
} io, util, sql etc.
Java Interface Example
Here, we will have the detailed learning of creating and using user-defined
In this example, the Printable interface has only one method, and its packages.
implementation is provided in the A6 class.
Advantage of Java Package
interface printable{
1) Java package is used to categorize the classes and interfaces so that they
void print(); can be easily maintained.
}
2) Java package provides access protection.
class A6 implements printable{
public void print(){System.out.println("Hello");} 3) Java package removes naming collision.