3rd Unit Inheritance Abstract
3rd Unit Inheritance Abstract
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
o Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are
created.
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.
o 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.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the
existing class when you create a new class. You can use the same fields and methods already defined in the previous class.
The syntax of Java Inheritance
1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }
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.
In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass.
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.
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.
File: TestInheritance.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}
Output:
barking...
eating...
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below, BabyDog
class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance.
Syntax
13. Class Superclass-name
14. {
15. //methods and fields
16. }
17. class Subclass 1-name extends Superclass-name
18. {
19. //methods and fields
20. }
21. class Subclass 2-name extends Subclass 1-name
22. {
23. //methods and fields
24. }
Example
File: TestInheritance2.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given below, Dog and Cat
classes inherits the Animal class, so there is hierarchical inheritance.
Syntax
25. Class Superclass-name
26. {
27. //methods and fields
28. }
29. class Subclass 1-name extends Superclass-name
30. {
31. //methods and fields
32. }
33. class Subclass 2-name extends Superclass-name
34. {
35. //methods and fields
36. }
File: TestInheritance3.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}
Output:
meowing...
eating...
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. }
5) Hybrid Inheritance
There is a combination of either single , multilevel , hierarchical or multiple Inheritance is called Hybrid Inheritance.or Combination
of two or more than 2 types of inheritance is called as Hybrid inheritance.Interface keyword is used to derive the example and to
inherite the interface the implementation keyword is used .
Example 1: If we create an object of the superclass, we can access only the members of the superclass. We cannot
access the subclass members by creating an object of superclass.
package inheritance;
public class Parentclass
{
void m1()
{
System.out.println("Superclass m1 method");
}
}
public class Childclass extends Parentclass
{
void m2()
{
System.out.println("Childclass m2 method");
}
}
public class Test {
public static void main(String[] args)
{
// Creating an object of superclass.
Parentclass p = new Parentclass();
p.m1();
// Here, subclass members are not available to superclass.
// So, we cannot access them using superclass reference variable.
}
}
Output:
Superclass m1 method
As you can observe in this example, the subclass members cannot be accessed by using the superclass object reference
variable. But if we create an object of the subclass, we can access all the members of both superclass and subclass.
program where we will access both superclass and subclass members by creating an object of the baseclass.
Example 2:
package inheritance;
public class Parentclass
{
void m1()
{
System.out.println("Superclass m1 method");
}
}
public class Childclass extends Parentclass
{
void m2()
{
System.out.println("Childclass m2 method");
}
}
public class Test {
public static void main(String[] args)
{
// Creating an object of subclass.
Childclass c = new Childclass();
// Accessing superclass and subclass members using subclass object reference variable.
c.m1();
c.m2();
}
}
Output:
Superclass m1 method
Childclass m2 method
As you can see in the above program, we have easily accessed members of the superclass as well as subclass by
creating an object of subclass. Therefore, we always create an object of subclass in inheritance.
Super class and sub class Members with Same Name
superclass and subclass members have the same name. by default, only the members of subclass are accessible.
Example:
package inheritance;
public class Number
{
int x = 20;
void display()
{
System.out.println("X = " +x);
}
}
public class Number2 extends Number
{
int x = 50;
void display()
{
System.out.println("X = " +x);
}
}
public class NumberTest {
public static void main(String[] args)
{
// Creating an instance of subclass.
Number2 n = new Number2();
n.display();
}
}
Output:
X = 50
We can access superclass members from the subclass using the keyword “super“. The keyword “super” refers to
superclass members from the subclass. We can apply it with superclass variables, methods, and constructors.
Let’s take the above example where we will access the superclass method and instance variable by using a super
keyword from the subclass.
package inheritance;
public class Number
{
int x = 20;
void display()
{
System.out.println("X = " +x);
}
}
public class Number2 extends Number
{
int x = 50;
void display()
{
System.out.println("X = " +super.x); // Accessing superclass instance variable using super keyword.
System.out.println("X = " +x);
}
}
public class NumberTest {
public static void main(String[] args)
{
Number2 n = new Number2();
n.display();
}
}
Output:
X = 20
X = 50
o Method overriding is used to provide the specific implementation of a method which is already provided by its
superclass.
o Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
When a method in a subclass has the same name, the same parameters or signature, and the same return type(or sub-
type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class.
The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a
parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the
subclass is used to invoke the method, then the version in the child class will be executed. In other words, it is the
type of the object being referred to (not the type of the reference variable) that determines which version of an
overridden method will be executed.
Example of Method Overriding in Java
// Base Class
class Parent {
void show() { System.out.println("Parent's show()"); }
}
// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
@Override void show()
{
System.out.println("Child's show()");
}
}
// Driver class
class Main {
public static void main(String[] args)
{
// If a Parent type reference refers
// to a Parent object, then Parent's
// show is called
Parent obj1 = new Parent();
obj1.show();
Output
Parent's show()
Child's show()
1. toString() method
The toString() provides a String representation of an object and is used to convert an object to a String. The default
toString() method for class Object returns a string consisting of the name of the class of which the object is an
instance, the at-sign character `@’, and the unsigned hexadecimal representation of the hash code of the object. In
other words, it is defined as:
// Default behavior of toString() is to print class name, then
// @, then unsigned hexadecimal representation of the hash code
// of the object
For every object, JVM generates a unique number which is a hashcode. It returns distinct integers for distinct
objects. A common misconception about this method is that the hashCode() method returns the address of the object,
which is not correct. It converts the internal address of the object to an integer by using an algorithm. The
hashCode() method is native because in Java it is impossible to find the address of an object, so it uses native
languages like C/C++ to find the address of the object.
Use of hashCode() method
It returns a hash value that is used to search objects in a collection. JVM(Java Virtual Machine) uses the hashcode
method while saving objects into hashing-related data structures like HashSet, HashMap, Hashtable, etc. The main
advantage of saving objects based on hash code is that searching becomes easy.
Note: Override of hashCode() method needs to be done such that for every object we generate a unique number. For
example, for a Student class, we can return the roll no. of a student from the hashCode() method as it is unique.
Java
// Constructor
Student()
{
roll_no = last_roll;
last_roll++;
}
// Overriding hashCode()
@Override public int hashCode() { return roll_no; }
// Driver code
public static void main(String args[])
{
Student s = new Student();
Output :
Student@64
Student@64
Note that 4*160 + 6*161 = 100
3. equals(Object obj) method
It compares the given object to “this” object (the object on which the method is called). It gives a generic way to
compare objects for equality. It is recommended to override the equals(Object obj) method to get our own equality
condition on Objects. For more on the override of equals(Object obj) method refer – Overriding equals method in
Java
Note: It is generally necessary to override the hashCode() method whenever this method is overridden, so as to
maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.
4. getClass() method
It returns the class object of “this” object and is used to get the actual runtime class of the object. It can also be used
to get metadata of this class. The returned Class object is the object that is locked by static synchronized methods of
the represented class. As it is final so we don’t override it.
Java
Output:
Class of Object obj is : java.lang.String
Note: After loading a .class file, JVM will create an object of the type java.lang.Class in the Heap area. We can use
this class object to get Class level information. It is widely used in Reflection
5. finalize() method
This method is called just before an object is garbage collected. It is called the Garbage Collector on an object when
the garbage collector determines that there are no more references to the object. We should override finalize()
method to dispose of system resources, perform clean-up activities and minimize memory leaks. For example, before
destroying the Servlet objects web container, always called finalize method to perform clean-up activities of the
session.
Note: The finalize method is called just once on an object even though that object is eligible for garbage collection
multiple times.
Java
// Java program to demonstrate working of finalize()
t = null;
System.out.println("end");
}
Output:
1510467688
end
finalize method called
6. clone() method
It returns a new object that is exactly the same as this object. For clone() method refer Clone().
1. class Student18 implements Cloneable{
2. int rollno;
3. String name;
4.
5. Student18(int rollno,String name){
6. this.rollno=rollno;
7. this.name=name;
8. }
9.
10. public Object clone()throws CloneNotSupportedException{
11. return super.clone();
12. }
13.
14. public static void main(String args[]){
15. try{
16. Student18 s1=new Student18(101,"amit");
17.
18. Student18 s2=(Student18)s1.clone();
19.
20. System.out.println(s1.rollno+" "+s1.name);
21. System.out.println(s2.rollno+" "+s2.name);
22.
23. }catch(CloneNotSupportedException c){}
24.
25. }
26. }
Test it Now
Output:101 amit
101 amit
Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single action in 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 you overload a static method in Java, it is the example of compile time polymorphism. Here, we will focus on
runtime polymorphism in java.
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is
resolved at runtime rather than compile-time.
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.
Let's first understand the upcasting before Runtime Polymorphism.
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example:
1. class A{}
2. class B extends A{}
1. A a=new B();//upcasting
For upcasting, we can use the reference variable of class type or an interface type. For Example:
1. interface I{}
2. class A{}
3. class B extends A implements I{}
Here, the relationship of B class would be:
B IS-A A
B IS-A I
B IS-A Object
Since Object is the root class of all classes in Java, so we can write B IS-A Object.
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.
Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
1. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splendor extends Bike{
5. void run(){System.out.println("running safely with 60km");}
6.
7. public static void main(String args[]){
8. Bike b = new Splendor();//upcasting
9. b.run();
10. }
11. }
utput:
running safely with 60km.
It is also known as static polymorphism. This type of polymorphism is achieved by function overloading or operator
overloading.
Note: But Java doesn’t support the Operator Overloading.
Method Overloading
When there are multiple functions with the same name but different parameters then these functions are said to
be overloaded. Functions can be overloaded by changes in the number of arguments or/and a change in the type of
arguments.
Example 1:
Java
// Class 1
// Helper class
class Helper {
// Method 2
// With same name but with 2 double parameters
static double Multiply(double a, double b)
{
// Returns product of double numbers
return a * b;
}
}
// Class 2
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Calling method by passing
// input as in arguments
System.out.println(Helper.Multiply(2, 4));
System.out.println(Helper.Multiply(5.5, 6.3));
}
}
Output
8
34.65
Static Binding and Dynamic Binding
Connecting a method call to the method body is known as binding.
There are two types of binding
1. Static Binding (also known as Early Binding).
2. Dynamic Binding (also known as Late Binding).
Understanding Type
1. class Dog{
2. public static void main(String args[]){
3. Dog d1;//Here d1 is a type of Dog
4. }
5. }
3) Objects have a type
1. class Animal{}
2.
3. class Dog extends Animal{
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. }
7. }
Here d1 is an instance of Dog class, but it is also an instance of Animal.
static binding
When type of the object is determined at compiled time(by the compiler), it is known as static binding.
If there is any private, final or static method in a class, there is static binding.
Example of static binding
1. class Dog{
2. private void eat(){System.out.println("dog is eating...");}
3.
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. d1.eat();
7. }
8. }
Dynamic binding
1. class Animal{
2. void eat(){System.out.println("animal is eating...");}
3. }
4.
5. class Dog extends Animal{
6. void eat(){System.out.println("dog is eating...");}
7.
8. public static void main(String args[]){
9. Animal a=new Dog();
10. a.eat();
11. }
12. }
Output:dog is eating...
In the above example object type cannot be determined by the compiler, because the instance of Dog is also an instance of
Animal.So compiler doesn't know its type, only its base type.
Generics in Java
Generics
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be
a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different
data types. An entity such as class, interface, or method that operates on a parameterized type is a generic entity.
Why Generics?
The Object is the superclass of all other classes, and Object reference can refer to any object. These features lack type
safety. Generics add that type of safety feature. We will discuss that type of safety feature in later examples.
Generics in Java are similar to templates in C++. For example, classes like HashSet, ArrayList, HashMap, etc., use
generics very well. There are some fundamental differences between the two approaches to generic types.
Generic Class
Like C++, we use <> to specify parameter types in generic class creation. To create objects of a generic class, we use
the following syntax.
// To create an instance of generic class
BaseType <Type> obj = new BaseType <Type>()
Output
15
GeeksForGeeks
Generic Functions:
We can also write generic functions that can be called with different types of arguments based on the type of arguments
passed to the generic method. The compiler handles each method.
Java
// Java program to show working of user defined
// Generic functions
class Test {
// A Generic method example
static <T> void genericDisplay(T element)
{
System.out.println(element.getClass().getName()
+ " = " + element);
}
// Driver method
public static void main(String[] args)
{
// Calling generic method with Integer argument
genericDisplay(11);
The type parameters naming conventions are important to learn generics thoroughly. The common type parameters are
as follows:
T – Type
E – Element
K – Key
N – Number
V – Value
Advantages of Generics:
Programs that use Generics has got many benefits over non-generic code.
1. Code Reuse: We can write a method/class/interface once and use it for any type we want.
2. Type Safety: Generics make errors to appear compile time than at run time (It’s always better to know problems in
your code at compile time rather than making your code fail at run time). Suppose you want to create an ArrayList that
store name of students, and if by mistake the programmer adds an integer object instead of a string, the compiler allows
it. But, when we retrieve this data from ArrayList, it causes problems at runtime.
Java
// Java program to demonstrate that NOT using
// generics can cause run time exceptions
import java.util.*;
class Test
{
public static void main(String[] args)
{
// Creatinga an ArrayList without any type specified
ArrayList al = new ArrayList();
al.add("Sachin");
al.add("Rahul");
al.add(10); // Compiler allows this
String s1 = (String)al.get(0);
String s2 = (String)al.get(1);
When defining ArrayList, we can specify that this list can take only String objects.
Java
class Test
{
public static void main(String[] args)
{
// Creating a an ArrayList with String specified
ArrayList <String> al = new ArrayList<String> ();
al.add("Sachin");
al.add("Rahul");
String s1 = (String)al.get(0);
String s2 = (String)al.get(1);
String s3 = (String)al.get(2);
}
}
Output:
15: error: no suitable method found for add(int)
al.add(10);
^
3. Individual Type Casting is not needed: If we do not use generics, then, in the above example, every time we retrieve
data from ArrayList, we have to typecast it. Typecasting at every retrieval operation is a big headache. If we already know
that our list only holds string data, we need not typecast it every time.
Java
import java.util.*;
class Test {
public static void main(String[] args)
{
// Creating a an ArrayList with String specified
ArrayList<String> al = new ArrayList<String>();
al.add("Sachin");
al.add("Rahul");
swap(j, j + 1, a);
}
}
}
for (T i : a)
{
System.out.print(i + ", ");
}
System.out.println();
Output
Sorted Integer array : 6, 22, 41, 50, 58, 100,
Sorted Character array : a, c, d, g, t, v, x,
Sorted String array : Abhinay, Bharat, Chandu, Kalam, Rohit, Sam, Virat,
Here, we have created a generics method. This same method can be used to perform operations on integer data, string
data, and so on.
Syntax:
larger_data_type variable_name = smaller_data_type_variable;
Example:
1. public class WideningTypeCastingExample
2. {
3. public static void main(String[] args)
4. {
5. int x = 7;
6. //automatically converts the integer type into long type
7. long y = x;
8. //automatically converts the long type into float type
9. float z = y;
10. System.out.println("Before conversion, int value "+x);
11. System.out.println("After conversion, long value "+y);
12. System.out.println("After conversion, float value "+z);
13. }
14. }
Output
Syntax:
smaller_data_type variable_name = (smaller_data_type) larger_data_type_variable;
Example:
1. public class NarrowingTypeCastingExample
2. {
3. public static void main(String args[])
4. {
5. double d = 166.66;
6. //converting double data type into long data type
7. long l = (long)d;
8. //converting long data type into int data type
9. int i = (int)l;
10. System.out.println("Before conversion: "+d);
11. //fractional part lost
12. System.out.println("After conversion into long type: "+l);
13. //fractional part lost
14. System.out.println("After conversion into int type: "+i);
15. }
16. }
Output
Explicit Upcasting
Upcasting is the process of casting a subtype to a supertype in the inheritance tree’s upward direction. When a sub-class
object is referenced by a superclass reference variable, an automatic process is triggered without any further effort.
Example:
Java
class Animal {
public void makeSound()
{
System.out.println("The animal makes a sound");
}
}
Explicit Downcasting
When a subclass type refers to an object of the parent class, the process is referred to as downcasting. If it is done
manually, the compiler issues a runtime ClassCastException error. It can only be done by using the instanceof operator.
Only the downcast of an object that has already been upcast is possible.
Example:
Java
class GFG {
public static void main(String[] args)
{
Animal animal = new Cat();
animal.eat();
// Explicit downcasting
Cat cat = (Cat)animal;
cat.meow();
}
}
Output
The animal is eating.
The cat is meowing.
Java instanceof
The java instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or
interface).
The instanceof in java is also known as type comparison operator because it compares the instance with type. It returns
either true or false. If we apply the instanceof operator with any variable that has null value, it returns false.
Let's see the simple example of instance operator where it tests the current class.
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);//true
}
}
Output:true
An object of subclass type is also a type of parent class. For example, if Dog extends Animal then object of Dog
can be referred by either Dog or Animal class.
class Animal{}
class Dog1 extends Animal{//Dog inherits Animal
public static void main(String args[]){
Dog1 d=new Dog1();
System.out.println(d instanceof Animal);//true
}
}
Output:true
instanceof in java with a variable that have null value
If we apply instanceof operator with a variable that have null value, it returns false. Let's see the example given below
where we apply instanceof operator with the variable that have null value.
class Dog2{
public static void main(String args[]){
Dog2 d=null;
System.out.println(d instanceof Dog2);//false
}
}
A class which is declared with the abstract keyword is known as an abstract class in Java
It can have abstract and non-abstract methods (method with the body).
Before learning the Java abstract class, let's understand the abstraction in Java first.
Abstraction in Java
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.
2. Interface (100%)
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It
needs to be extended and its method implemented. It cannot be instantiated.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors
and static methods also.
o It can have final methods which will force the subclass not to change the body of the method.
Example of abstract class
In this example, Bike is an abstract class that contains only one abstract method run. Its implementation is provided by
the Honda class.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Output:
running safely
Understanding the real scenario of Abstract class
In this example, Shape is the abstract class, and its implementation is provided by the Rectangle and Circle classes.
Mostly, we don't know about the implementation class (which is hidden to the end user), and an object of the
implementation class is provided by the factory method.
A factory method is a method that returns the instance of the class. We will learn about the factory method later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be invoked.
File: TestAbstraction1.java
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
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 achieve abstraction and multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body.
There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an
interface are declared with the empty body, and all the fields are public, static and final by default. A class that
implements an interface must implement all the methods declared in the interface.
Syntax:
interface <interface_name>{
As shown in the figure given below, a class extends another class, an interface extends another interface, but a class
implements an interface.
Java Interface Example
In this example, the Printable interface has only one method, and its implementation is provided in the A6 class.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
Output:
Hello
In this example, the Drawable interface has only one method. Its implementation is provided by Rectangle and Circle
classes. In a real scenario, an interface is defined by someone else, but its implementation is provided by different
implementation providers. Moreover, it is used by someone else. The implementation part is hidden by the user who
uses the interface.
File: TestInterface1.java
Output:
drawing circle
Let's see another example of java interface which provides the implementation of Bank interface.
File: TestInterface2.java
1. interface Bank{
2. float rateOfInterest();
3. }
4. class SBI implements Bank{
5. public float rateOfInterest(){return 9.15f;}
6. }
7. class PNB implements Bank{
8. public float rateOfInterest(){return 9.7f;}
9. }
10. class TestInterface2{
11. public static void main(String[] args){
12. Bank b=new SBI();
13. System.out.println("ROI: "+b.rateOfInterest());
14. }}
Output:
ROI: 9.15
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple inheritance.
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
Q) Multiple inheritance is not supported through class in java, but it is possible by an interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in the case of class because of
ambiguity. However, it is supported in case of an interface because there is no ambiguity. It is because its
implementation is provided by the implementation class. For example:
interface Printable{
void print();
}
interface Showable{
void print();
}
Output:
Hello
As you can see in the above example, Printable and Showable interface have same methods but its implementation is
provided by class TestTnterface1, so there is no ambiguity.
Interface inheritance
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();
}
}
Output:
Hello
Welcome
Java Package
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.
Here, we will have the detailed learning of creating and using user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
If you are not using any IDE, you need to follow the syntax given below:
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any directory name like /home
(in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package within the same directory, you can
use . (dot).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
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();
}
}
Output:Hello
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();
}
}
Output:Hello
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.
It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello
If you import a package, all the classes and interface of that package will be imported excluding the classes and
interfaces of the subpackages. Hence, you need to import the subpackage as well.
Note: Sequence of the program must be package then import then class.
Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in the Java Development Environment.
The library contains components for managing input, database programming, and much much more. The complete list
can be found at Oracles website: https://docs.oracle.com/javase/8/docs/api/.
The library is divided into packages and classes. Meaning you can either import a single class (along with its methods
and attributes), or a whole package that contain all the classes that belong to the specified package.
To use a class or a package from the library, you need to use the import keyword:
Syntax
Import a Class
If you find a class you want to use, for example, the Scanner class, which is used to get user input, write the following
code:
Example
importjava.util.Scanner;
In the example above, java.util is a package, while Scanner is a class of the java.util package.
To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class
documentation. In our example, we will use the nextLine() method, which is used to read a complete line:
Example
importjava.util.Scanner;
classMyClass{
publicstaticvoidmain(String[] args){
Scanner myObj =newScanner(System.in);
System.out.println("Enter username");
String userName = myObj.nextLine();
System.out.println("Username is: "+ userName);
}
}