0% found this document useful (0 votes)
82 views39 pages

3rd Unit Inheritance Abstract

Inheritance in Java allows classes to inherit properties and behaviors from parent classes. There are three types of inheritance in Java: single inheritance where a subclass inherits from one superclass, multilevel inheritance where a subclass inherits from another subclass that inherits from a superclass, and hierarchical inheritance where multiple subclasses inherit from a common superclass. Multiple inheritance is not supported in Java through classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views39 pages

3rd Unit Inheritance Abstract

Inheritance in Java allows classes to inherit properties and behaviors from parent classes. There are three types of inheritance in Java: single inheritance where a subclass inherits from one superclass, multilevel inheritance where a subclass inherits from another subclass that inherits from a superclass, and hierarchical inheritance where multiple subclasses inherit from a common superclass. Multiple inheritance is not supported in Java through classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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.
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.

Java Inheritance Example

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.

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 one class inherits multiple classes, it is known as multiple inheritance. For Example:

Single Inheritance Example


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 the single inheritance.
Syntax
5. Class Superclass-name
6. {
7. //methods and fields
8. }
9. class Subclass-name extends Superclass-name
10. {
11. //methods and fields
12. }

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...

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 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.
Syntax
37. Class Superclass 1-name
38. {
39. //methods and fields
40. }
41. Class Superclass 2-name
42. {
43. //methods and fields
44. }
45. class Subclass 1-name extends Superclass 1-name, Superclass 2-name
46.
47. {
48. //methods and fields
49. }
50. Example

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 .

Superclass and subclass


A class that is used to create a new class is called superclass. In the words, the class from where a subclass inherits the
features is called superclass. It is also called a base class or parent class. A class that inherits all the members (fields,
method, and nested classes) from the other class is called subclass. In simple words, a newly created class is called
subclass. It is also called a derived class, child class, or extended class.

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

Method Overriding in Java


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.
Usage of Java Method Overriding

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

// Java program to demonstrate


// 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();

// If a Parent type reference refers


// to a Child object Child's show()
// is called. This is called RUN TIME
// POLYMORPHISM.
Parent obj2 = new Child();
obj2.show();
}
}

Output
Parent's show()
Child's show()

Object Class in Java


Object class is present in java.lang package. Every class in Java is directly or indirectly derived from
the Object class. If a class does not extend any other class then it is a direct child class of Object and if extends
another class then it is indirectly derived. Therefore the Object class methods are available to all Java classes. Hence
Object class acts as a root of the inheritance hierarchy in any Java Program. Program.

The Object class provides multiple methods which are as follows:


 tostring() method
 hashCode() method
 equals(Object obj) method
 finalize() method
 getClass() method
 clone() method
 wait(), notify() notifyAll() methods

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

public String toString()


{
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
It is always recommended to override the toString() method to get our own String representation of Object. For
more on override of toString() method refer – Overriding toString() in Java
Note: Whenever we try to print any Object reference, then internally toString() method is called.
Student s = new Student();

// Below two statements are equivalent


System.out.println(s);
System.out.println(s.toString());
2. hashCode() method

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

// Java program to demonstrate working of


// hashCode() and toString()

public class Student {


static int last_roll = 100;
int roll_no;

// 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();

// Below two statements are equivalent


System.out.println(s);
System.out.println(s.toString());
}
}

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

// Java program to demonstrate working of getClass()

public class Test {


public static void main(String[] args)
{
Object obj = new String("GeeksForGeeks");
Class c = obj.getClass();
System.out.println("Class of Object obj is : "
+ c.getName());
}
}

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()

public class Test {


public static void main(String[] args)
{
Test t = new Test();
System.out.println(t.hashCode());

t = null;

// calling garbage collector


System.gc();

System.out.println("end");
}

@Override protected void finalize()


{
System.out.println("finalize method called");
}
}

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 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.

Example of Java Runtime Polymorphism

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.

Compile-Time Polymorphism in Java

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

// Java Program for Method overloading


// By using Different Types of Arguments

// Class 1
// Helper class
class Helper {

// Method with 2 integer parameters


static int Multiply(int a, int b)
{
// Returns product of integer numbers
return a * b;
}

// 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

Let's understand the type of instance.


1) variables have a type

Each variable has a type, it may be primitive and non-primitive.


1. int data=30;
Here data variable is a type of int.
2) References have a 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

An object is an instance of particular java class,but it is also an instance of its superclass.

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

When type of the object is determined at run-time, it is known as dynamic binding.


Example of 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.

Types of Java Generics


Generic Method: Generic Java method takes a parameter and returns some value after performing a task. It is exactly
like a normal function, however, a generic method has type parameters that are cited by actual type. This allows the
generic method to be used in a more general way. The compiler takes care of the type of safety which enables
programmers to code easily since they do not have to perform long, individual type castings.
Generic Classes: A generic class is implemented exactly like a non-generic class. The only difference is that it
contains a type parameter section. There can be more than one type of parameter, separated by a comma. The classes,
which accept one or more parameters, ?are known as parameterized classes or parameterized 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>()

// Java program to show working of user defined


// Generic classes

// We use < > to specify Parameter type


class Test<T> {
// An object of type T is declared
T obj;
Test(T obj) { this.obj = obj; } // constructor
public T getObject() { return this.obj; }
}

// Driver class to test above


class Main {
public static void main(String[] args)
{
// instance of Integer type
Test<Integer> iObj = new Test<Integer>(15);
System.out.println(iObj.getObject());

// instance of String type


Test<String> sObj
= new Test<String>("GeeksForGeeks");
System.out.println(sObj.getObject());
}
}

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);

// Calling generic method with String argument


genericDisplay("GeeksForGeeks");

// Calling generic method with double argument


genericDisplay(1.0);
}
}
Output
java.lang.Integer = 11
java.lang.String = GeeksForGeeks
java.lang.Double = 1.0

Generics Work Only with Reference Types:


When we declare an instance of a generic type, the type argument passed to the type parameter must be a reference
type. We cannot use primitive data types like int, char.
Test<int> obj = new Test<int>(20);
The above line results in a compile-time error that can be resolved using type wrappers to encapsulate a primitive type.
But primitive type arrays can be passed to the type parameter because arrays are reference types.
ArrayList<int[]> a = new ArrayList<>();

Type Parameters in Java Generics

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);

// Causes Runtime Exception


String s3 = (String)al.get(2);
}
}
Output :
Exception in thread "main" java.lang.ClassCastException:
java.lang.Integer cannot be cast to java.lang.String
at Test.main(Test.java:19)

How do Generics Solve this Problem?

When defining ArrayList, we can specify that this list can take only String objects.

Java

// Using Java Generics converts run time exceptions into


// compile time exception.
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");

// Now Compiler doesn't allow this


al.add(10);

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

// We don't need to typecast individual members of ArrayList

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");

// Typecasting is not needed


String s1 = al.get(0);
String s2 = al.get(1);
}
}
4. Generics Promotes Code Reusability: With the help of generics in Java, we can write code that will work with
different types of data. For example,
Let’s say we want to Sort the array elements of various data types like int, char, String etc.
Basically we will be needing different functions for different data types.
For simplicity, we will be using Bubble sort.
But by using Generics, we can achieve the code reusability feature.
Java

public class GFG {

public static void main(String[] args)


{

Integer[] a = { 100, 22, 58, 41, 6, 50 };

Character[] c = { 'v', 'g', 'a', 'c', 'x', 'd', 't' };

String[] s = { "Virat", "Rohit", "Abhinay", "Chandu","Sam", "Bharat", "Kalam" };

System.out.print("Sorted Integer array : ");


sort_generics(a);

System.out.print("Sorted Character array : ");


sort_generics(c);
System.out.print("Sorted String array : ");
sort_generics(s);

public static <T extends Comparable<T> > void sort_generics(T[] a)


{

//As we are comparing the Non-primitive data types


//we need to use Comparable class

//Bubble Sort logic


for (int i = 0; i < a.length - 1; i++) {

for (int j = 0; j < a.length - i - 1; j++) {

if (a[j].compareTo(a[j + 1]) > 0) {

swap(j, j + 1, a);
}
}
}

// Printing the elements after sorted

for (T i : a)
{
System.out.print(i + ", ");
}
System.out.println();

public static <T> void swap(int i, int j, T[] a)


{
T t = a[i];
a[i] = a[j];
a[j] = t;
}

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.

Casting objects in java


An object can be converted from one data type to another using typecasting,also known as type conversion.
Type Casting in Java
Typecasting in Java is the process of converting one data type to another data type in both ways manually and
automatically using the casting operator. The automatic conversion is done by the compiler and manual conversion
performed by the programmer.
Syntax:
<datatype> variableName = (<datatype>) value;
Types of Type Casting
There are two types of Type Casting in java:
 Widening Type Casting
 Narrow Type Casting

Widening Type Casting


A lower data type is transformed into a higher one by a process known as widening type casting. Implicit type casting
and casting down are some names for it. It is also known as implicit conversion or casting down.It is done automatically. It
occurs naturally. Since there is no chance of data loss, it is secure. Widening Type casting occurs when:
 The target type must be larger than the source type.
 Both data types must be compatible with each other.

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

Before conversion, the value is: 7


After conversion, the long value is: 7
After conversion, the float value is: 7.0

Narrow Type Casting


The Larger data type is Transformed into a smaller one is known as narrowing type casting. It is also known as explicit
conversion or casting up. It is done manually by the programmer. If we do not perform casting then the compiler
reports a compile-time error. Narrowing type casting is unsafe because data loss might happen due to the lower data
type’s smaller range of permitted values. A cast operator assists in the process of explicit casting.

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

Before conversion: 166.66


After conversion into long type: 166
After conversion into int type: 166

Types of Explicit Casting

Mainly there are two types of Explicit Casting:


 Explicit Upcasting
 Explicit Downcasting

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

// Java Program to demonstrate Explicit Upcasting


import java.io.*;

class Animal {
public void makeSound()
{
System.out.println("The animal makes a sound");
}
}

class Dog extends Animal {


public void makeSound()
{
System.out.println("The dog barks");
}

public void fetch()


{
System.out.println("The dog fetches a ball");
}
}
class GFG {
public static void main(String[] args)
{ // Upcasting
Animal animal = new Dog();
// Calls the overridden method in Dog class
animal.makeSound();
// This would give a compile error as fetch() is not
// a method in Animal class
// animal.fetch();
}
}
Output
The dog barks

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

// Java Program to demonstrate Explicit downcasting


import java.io.*;
class Animal {
public void eat()
{
System.out.println("The animal is eating.");
}
}

class Cat extends Animal {


public void meow()
{
System.out.println("The cat is meowing.");
}
}

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.

Simple example of java instanceof

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.

Another example of java instanceof operator

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
}
}

Abstract class in Java

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.

Abstraction lets you focus on what the object


does instead of how it does it.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)

2. Interface (100%)

Abstract class in Java

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

1. abstract class A{}

Abstract Method in Java


A method which is declared as abstract and does not have implementation is known as an abstract method.
Example of abstract method

1. abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract method

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

abstract class Shape{


abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape() method
s.draw();
}
}

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.

It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.

o By interface, we can support the functionality of multiple inheritance.

o It can be used to achieve loose coupling.

How to declare an interface?

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>{

// declare constant fields


// declare methods that abstract
// by default.
}

The relationship between classes and interfaces

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");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}

Output:

Hello

Java Interface Example: Drawable

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

//Interface declaration: by first user


interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
d.draw();
}}

Output:

drawing circle

Java Interface Example: Bank

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

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 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");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:Hello
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();
}

class TestInterface3 implements Printable, Showable{


public void print(){System.out.println("Hello");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
obj.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

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();
}
}

Output:

Hello
Welcome

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.

Here, we will have the detailed learning of creating and using user-defined packages.

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.


Simple example of java package

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");
}
}

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

1. javac -d directory javafilename

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).

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java


To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents the current folder.

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;

3. fully qualified name.


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.

Example of package that import the packagename.*

//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.

Example of package by import package.classname

//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

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.

It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class.

Example of package by import fully qualified name

//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

Note: If you import a package, subpackages will not be imported.

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

importpackage.name.Class;// Import a single class

importpackage.name.*;// Import the whole package

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

Using the Scanner class to get user input:

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);
}
}

You might also like