Unit 2
Unit 2
Inheritance in Java
* 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
Why use inheritance in java
o 1.For Method Overriding
---→(so runtime polymorphism can be achieved).
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.
Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.
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 args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance
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 args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical
inheritance. 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 args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
super key word
The super keyword in Java is a reference variable which is used to refer
immediate parent class object.
While one of Java's strengths is the concept of inheritance, in which one class
can derive from another, sometimes it's desirable to prevent inheritance by
another class. To prevent inheritance, use the keyword "final" when creating
the class.
The main reason to prevent inheritance is to make sure the way a class behaves
is not corrupted by a subclass.
Suppose we have a class Account and a subclass that extends it,
OverdraftAccount. Class Account has a method getBalance()
This means that the Account class cannot be a superclass, and the OverdraftAccount class can
no longer be its subclass.
Sometimes, you may wish to limit only certain behaviors of a superclass to avoid corruption
by a subclass. For example, OverdraftAccount still could be a subclass of Account, but it should
be prevented from overriding the getBalance() method.
public class Account {
private double balance;
public final double getBalance()
{
return this.balance;
}
}
final is a non-access modifier for Java elements. The final modifier is used for
finalizing the implementations of classes, methods, and variables.
What are ways to Prevent Inheritance in Java Programming?
There are 2 ways to stop or prevent inheritance in Java programming.
By using final keyword with a class orBy using a private constructor in a class.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
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.
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
The relationship between classes and interfaces
A class extends another class, an interface extends another interface, but
a class implements an interface.
interface inter
{
int a=10,b=20;
public void add();
}
class c1 implements inter
{
public void add()
{
int sum=a+b;
System.out.println("Sum of numbers is:" +sum);
}
public static void main(String[] srgs)
{
c1 obj= new c1();
obj.add();
}
} output: Sum of numbers is: 30
interface Drawable{
void draw();
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();
d.draw();
Drawable d1=new Rectangle();
d1.draw();
}} output: drawing circle
drawing rectangle
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple
interfaces, it is known as multiple inheritance.
interface inter public void sub()
{ {
int a=10,b=20; int r=c-d;
public abstract void add(); System.out.println(" Difference of numbers
} is :" +r);
interface inter1 }
{ public static void main(String[] args)
int c=20,d=10; {
public abstract void sub(); c1 obj=new c1();
} obj.add();
class c1 implements inter,inter1 obj.sub();
{ }
public void add() } Output: Sum of numbers is : 30
{ Difference of numbers is: 10
int sum=a+b;
System.out.println(" Sum of numbers
is :" +sum);
}
Interface inheritance
A class implements an interface, but one interface extends another
interface. interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
} Out put : Hello
}
Java Nested Interface
An interface, i.e., declared within another interface or class, is known as a
nested interface. The nested interfaces are used to group related interfaces
so that they can be easy to maintain.
Points to remember
...
}
} Syntax of nested interface which is declared within the
class
class class_name{
...
interface nested_interface_name{
...
}
}
Example of nested interface which is declared within the interface
interface Showable
{ public static void main(String args[])
void show(); {
interface Message c1 obj1=new c1();
{ obj1.msg();
void msg(); obj1.show();
} }
} }
class c1 implements Showable.Message
{ Output: Hello nested interface
public void msg() Welcome to nested interface
{
System.out.println("Hello nested interface");
}
public void show()
{
System.out.println(" Welcome to nested interface");
}
Java Default Methods
Java provides a facility to create default methods inside the interface. Methods
which are defined inside the interface and tagged with default are known as
default methods. These methods are non-abstract methods.
interface add class c1 implements add{
{ public void addition()
public void addition(); {
default void addition1() int i=1,j=4,k;
{ int a=1,b=2,c; k=i+j;
c=a+b; System.out.println(k); }
System.out.println(c); public static void main(String[] args)
} { add obj=new c1();
static void sub() obj.addition();
{ obj.addition1();
int l=20,m=10,n; add.sub();
n=l-m; }
System.out.println(n); } output:5
} 3
} 10
Difference between abstract class and interface
Abstract class Interface
1) Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods. Since Java 8, it can have default
and static methods also.
2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static and non-static Interface has only static and final variables.
variables.
4) Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class.
5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.
6) An abstract class can extend another Java class and implement An interface can extend another Java interface only.
multiple Java interfaces.
7) An abstract class can be extended using keyword "extends". An interface can be implemented using keyword "implements".
8) A Java abstract class can have class members like private, Members of a Java interface are public by default.
protected, etc.
9)Example:public abstract clasShape{ Example:
public abstract void draw(); public interface Drawable{
} void draw();
}
Java Package
A java package is a group of similar types of classes, interfaces and sub-
packages.
Package in java can be categorized in two form, built-in package and user-
defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io,
util, sql etc.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can
be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
1. Core Packages: Core Packages are predefined
packages given by Sun MicroSystems which begin with
“java”.
2. Extended Packages: Extended packages are also
predefined packages given by Sun Microsystems which
begin with “javax”.
3. Third-Party Packages: Third-Party Packages are also
predefined packages that are given by some other
companies as a part of Java Software.
Example:oracle.jdbc, com.mysql, etc
User-Defined Packages in Java
In Java, we can also create user-defined packages according to our
requirements. To create the user-defined packages we have to use a java
keyword called “package.
Rules:
1. While writing the package name we can specify packages in any number of
levels but specifying one level is mandatory.
2. The package statement must be written as the first executable statement in
the program.
3. We can write at most one package statement in the program
package Demo;
public class PackageDemo {
public static void main(String args[]) {
System.out.println("Have a Nice
Day...!!!");
}
}
How to access package from another package?
There are three ways to access the package from outside the package.
1)import package.*;
2)import package.classname;
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.
The import keyword is used to make the classes and interface of another
package accessible to the current package.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
2) Using packagename.classname
If you import package.classname then only declared class of this package will
be accessible.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified
name every time when you are accessing the class or interface.
//save by A.java
package pack; //save by B.java
public class A{ package mypack;
public void msg(){System.out.println("Hello");} class B{
} public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
C:\Users\MRUH\Desktop\javaex\package>javac -d . B.java
C:\Users\MRUH\Desktop\javaex\package>java pack.Simple
Subpackage in java
Package inside the package is called the subpackage. It should be created to
categorize the package further.
package pack.package;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}