Java Tutorial

Java Tutorial Java Features C++ vs Java Java History Java Hello World Java Development Kit Java Runtime Environment Java Virtual Machine Difference between JDK, JRE, and JVM Memory Areas in Java Java Operators Java Keywords Primitive Data Types Variables

Java Loops

Java Do While Loop Java While Loop Java For Loop Java Enhanced For Loop

Java Programs

Java Basic Programs Factorial Program in Java Fibonacci Series Program in Java Prime Number Program in Java Palindrome Number Program in Java Armstrong Number Program in Java Anagram Program in Java Pattern Programs in Java Calculator Program in Java Leap Year Program in Java Addition Program in Java Number Pattern Programs in Java Star Pattern Programs in Java Package Program in Java Pyramid Program in Java Sorting Program in Java String Palindrome Program in Java Even Odd Program in Java For Loop Program in Java If Else Program in Java Switch Case Program in Java GCD Program in Java LCM Program in Java Hello Program in Java Matrix Program in Java Menu Driven Program in Java Series Program in Java Client Server Program in Java Swapping Program in Java Pig Latin Program in Java Tower of Hanoi Program in Java Recursion Program in Java Matrix Multiplication Program in Java Perfect Number Program in Java Classes and Objects in Java Example Programs String Programs in Java Array Programs in Java Constructor Program in Java Inheritance Program in Java Abstract class Program in Java Interface Program in Java Encapsulation Program in Java Polymorphism Program in Java Exception Handling Program in Java Multithreading Program in Java Thread Program in Java Collection Programs in Java ArrayList Program in Java Stack Program in Java Applet Program in Java Swing Program in Java JDBC Program in Java How to run Java program in command prompt How to run Java program in Eclipse

Java Sorting

Sorting Algorithms in Java Merge Sort in Java Quick Sort in Java Bubble Sort in Java Insertion Sort in Java Selection Sort in Java Heap Sort in Java Radix Sort in Java Topological Sort in Java Bucket Sort in Java Counting Sort in Java

Java OOPs Concepts

OOPs - Object Oriented Programming Objects and Classes in Java Java Naming Conventions Constructors in Java Java this keyword Java static keyword Inheritance in Java Aggregation in Java Java super keyword Constructor Chaining and Constructor Overloading Java Polymorphism Static and Dynamic Binding in Java Java Abstraction Abstract class in Java Interface in Java Difference between Abstract class and Interface Java final keyword Packages in Java Access Modifiers in Java Java Wrapper classes Java Numbers Java Characters Java Integer Java Boolean Java Arrays Java Command Line Arguments Java strictfp Keyword Java Math

Java Strings

Java Strings Java String Methods StringBuilder in Java StringBuffer in Java Java Regular Expressions StringBuffer vs StringBuilder String vs StringBuffer String vs StringBuilder String Manipulation in Java Java String Concatenation How to Reverse a String in Java String Array in Java How to Compare Two Strings in Java How to Concatenate Two Strings in Java Why String in Immutable in Java java.lang.NumberFormatException for Input String String Pool in Java Java Generate Random String How to take String Input in Java Java String Interview Questions

Java Exceptions

Exception Handling in Java Java try catch Java throw Java throws Difference between throw and throws Java finally Java Custom Exception Java Exception Propagation

Garbage Collection

Automatic Resource Management in Java Java Garbage Collection Java finalize() Java gc() Difference between final, finally and finalize

Multithreading

Multithreading in Java Process and Thread in Java Basic Terms in Multithreading Java Thread creation Thread Scheduler in Java Java Thread class DeadLock in Java

Java IO

Java IO Java Read File Java BufferedWriter Java InputStreamReader Java File Java Read File Line By Line Java FileOutputStream Jar File in Java

Serialization

Java Serialization Java transient

Networking

Java Network Programming Java Socket Programming Java URL Java URLConnection HttpURLConnection in Java Java InetAddress Java DatagramSocket and Java DatagramPacket

AWT

Java AWT

Swing

Swing in Java

Java Collections

Collections in Java Java List Interface ArrayList in Java LinkedList in Java Vector in Java Stack in Java ArrayList vs LinkedList in Java ArrayList vs Vector in Java Java Set Interface HashSet in Java LinkedHashSet in Java TreeSet in Java Java Queue Interface PriorityQueue in Java ArrayDeque in Java Java Map Interface HashMap in Java LinkedHashMap in Java TreeMap in Java Dictionary in Java Hashtable in Java Properties in Java Collections class in Java Java Comparable Java Comparator Comparable vs Comparator in Java

Java Generics

Generics in Java

Java Annotations

Annotations in Java

Java JDBC

Java JDBC Tutorial

Java Differences

Java vs JavaScript Python vs Java Kotlin vs Java Java vs C++ C# vs Java Static vs Non-static in Java C vs Java int vs Integer in Java Stack vs Heap in Java Java Array vs ArrayList

How to

How to run Java program How to set path in Java How to check the Java version in cmd How to install Java in Windows 10 How to run Java program in cmd How to call a method in Java How to sort an array in Java How to iterate HashMap in Java How to write Java program How to create an array in Java How to create a package in Java How to generate random numbers in Java How to input String in Java How to create thread in Java How to find length of String in Java How to sort a string in Java How to use scanner in Java How to achieve multiple inheritance in Java How to run Java program in Eclipse How to call a function in Java How to create array of objects in Java How to create custom exception in Java How to achieve abstraction in Java How to call static method in Java

Java 8 Features

Java 8 Features Lambda Expressions in Java Functional Interface in Java Streams in Java Java Base64 Encoding and Decoding Parallel Arrays Sort in Java

Java 9 Features

Java 9 Tutorial Java 9 Try With Resources Java 9 Interface Private Method

Java Servlet Tutorial

Java Servlets Tutorial

Java JSP Tutorial

Java JSP Tutorial

Hibernate Tutorial

Hibernate Tutorial

Spring Tutorial

Spring Tutorial

Spring MVC Tutorial

Spring MVC Tutorial

Jenkins Tutorial

Jenkins Tutorial

Java Math Methods

Math.abs() Math.acos() Math.addExact() Math.asin() Math.atan () Math.atan2() Math.cbrt() Math.ceil() Math.copysign() Math.cos() Math.cosh() Math.decrementExact() Math.exp() Math.expm1() Math.floor() Math.floorDiv() Math.floorMod() Math.getExponent() Math.hypot() Math.IEEEremainder() Math.incrementExact() Math.log() Math.log10() Math.log1p() Math.max() Math.min() Math.multiplyExact() Math.multiplyFull() Math.negateExact() Math.nextAfter() Math.nextDown() Math.nextUp() Math.pow() Math.random() Math.rint() Math.round() Math.scalb() Math.signum() Math.sin() Math.sinh() Math.sqrt() Math.subtractExact() Math.tan() Math.tanh() Math.toDegrees() Math.toIntExact() Math.toRadians() Math.ulp()

Java String Methods

toCharArray() copyValueOf() endsWith() equals() equalsIgnoreCase() format() getBytes() getChars() hashCode() indexOf() intern() isEmpty() join() lastIndexOf() length() replace() replaceAll() replaceFirst() split() startsWith() subSequence() substring() toLowerCase() toUpperCase() trim() valueOf()

Java Conversion

Java Convert String to int Java Convert int to String Java Convert String to long Java Convert long to String Java Convert String to float Java Convert float to String Java Convert String to double Java Convert double to String Java Convert String to Date Java Convert Date to String Java Convert String to Object Java Convert Object to String Java Convert String to char Java Convert char to String Java Convert int to long Java Convert long to int

Misc

Functional Interfaces in Java Singleton class in Java Awesome explanation of Strings in Java Object class in Java Static class in Java All the important string methods in Java String Handling Method in Java What are Array strings in Java Advantages and Disadvantages of Strings in Java Big Decimal class in Java Class definition in Java Char and String differences in Java Difference between String, StringBuffer and StringBuilder in java Replace character in string Java String Coding Interview Questions in Java What is String in Java? String isnullorempty in Java String Matches in Java Trim Method in String Java Bean class in Java Libraries in Java Arithmetic Operations on String in Java Convert Char array to string in java Check whether Java is installed or not How to calculate time difference in Java How to stop execution after a certain time in Java Jagged Array in Java Java ArraylistRemove() Time Complexity Java Swing Time Picker Zigzag Array in Java

Inheritance Program in Java

Inheritance Program in Java

Inheritance is one of the important pillars of Object-Oriented Programming that facilitates parent-child relationships in programming. Using inheritance, we can create a new class with the help of an existing class. This newly created class is also known as the derived class, or child class, or subclass, whereas the existing class is known as the base class or parent class, or superclass. The child class acquires the characteristics of the parent class. Inheritance is widely used in the world of programming world as it manages the information in hierarchical order (parent to child, child to sub-child, and so on). The main advantages of using inheritance are:

1) Helps in achieving re-usability of code.

2) Facilitates method overriding in the child class.

Inheritance is mainly used where there is an IS-A relationship. For example,

  • Crow is a bird.
  • Python is a reptile.
  • An employee is a human being.
  • Apple is a fruit.
  • A Dentist is a doctor.

In the above examples, Crow, Python, Employee, Apple, and Dentist are the child classes, whereas Bird, Reptile, Human Being, Fruit, and Doctor are the parent classes. The Inheritance program in Java shows how the parent-child relationship is achieved via programming.

Syntax:

 class XYZ extends ABC
 {
 …
 …
 } 

In Java, the keyword extends is used to achieve inheritance. In the above code snippet, the class XYZ is acquiring the features of the class ABC. Therefore, XYZ is the child class, and ABC is the base class.

Re-usability of code in Inheritance

Consider the following code.

FileName: MainClass.java

 class Fruit
 {
    String fruitName;
 }
 // child class Apple is inheriting parent class Fruit
 class Apple extends Fruit
 {
 }
 // child class Banana is inheriting parent class Fruit
 class Banana extends Fruit
 {
 }
 public class Main
 {
 public static void main(String argvs[])
 {
     // creating object of the child class Apple
                Apple apple = new Apple();
                // assigning the fruit name
                apple.fruitName = "Apple";
                // displaying the fruit name
                System.out.println("Fruit name is " + apple.fruitName);
                // creating object of the child class Banana
                Banana banana = new Banana();
                // assinging the fruit name
                banana.fruitName = "Banana";
                // displaying the fruit name
                System.out.println("Fruit name is " + banana.fruitName);
 }
 } 

Output:

 Fruit name is Apple
 Fruit name is Banana 

Explanation: In the code, the string field fruitName is declared only in the Fruit class. The two-child classes: Apple and Banana, are inheriting from the Fruit class. Therefore, the string field fruitName is present in the class Apple and Banana. In the driver method, we have created two objects: one each for the class Apple and Banana. Using the created objects, we are accessing the field fruitName for both classes. Thus, we see that whatever we declare in the parent class, the child class automatically gets access to it. We do not have to make the declaration explicitly. This is how the re-usability of code is achieved. Similar to fields, in methods also we can do re-usability of code.

Method Overriding in Inheritance

The method defined in the parent class can get overridden in the child class. The overriding method means changing the definition of the method in the child class. Let’s understand with the help of a program.

FileName: MainClass.java

 class Fruit
 {
                // declaration of a string field
                String fruitName;
                // a method that tells about seeds in a fruit
                void seeds()
                {
                                System.out.println("Some fruit has no seeds. ");
                }
 }
 // child class Banana is inheriting the parent class Fruit
 class Banana extends Fruit
 {
                // overriding the method seeds() in the child class Banana
                @Override
                void seeds()
                {
                                System.out.println("Banana has no seeds. ");
                }
 }
 public class MainClass
 {
 // driver method
 public static void main(String argvs[])
 {
                // creating object of the child class Banana
                Banana banana = new Banana();
                // assinging the fruit name
                banana.fruitName = "Banana";
                // displaying the fruit name
                System.out.println("Fruit name is " + banana.fruitName);
                // invoking the method seeds() on the object banana
                banana.seeds();
 }
 } 

Output:

 Fruit name is Banana
 Banana has no seeds. 

Explanation: The method seeds() is being overridden in the Banana class. Note that, in overriding a method, the definition of the method changes, not it’s signature. Upon invoking the method seeds() on the object banana,  the overridden version of the method seeds() is called (observe the output). To stop the overriding, comment/ delete the method seeds() in the child class (do it yourself, and then observe what changes occur in the output.). Before overriding the method, it is a good practice to add “@Override”. This enhances the readability of the code. However, omitting “@Override” does not have any impact on the output.

Note: While overriding a method in Java, we cannot specify a weaker access specifier to an overridden method in the child class. Let’s see what happens if we add the keyword public in the method seeds() of the class Fruit.

FileName: MainClass.java

 class Fruit
 {
                // declaration of a string field
                String fruitName;
                // a method that tells about seeds in a fruit
                public void seeds() // added keyword public
                {
                                System.out.println("Some fruit has no seeds. ");
                }
 }
 // child class Banana is inheriting the parent class Fruit
 class Banana extends Fruit
 {
                // overriding the method seeds() in the child class Banana
                @Override
                void seeds()
                {
                                System.out.println("Banana has no seeds. ");
                }
 }
 public class MainClass
 {
 // driver method
 public static void main(String argvs[])
 {
                // creating object of the child class Banana
                Banana banana = new Banana();
                // assinging the fruit name
                banana.fruitName = "Banana Fruit";
                // displaying the fruit name
                System.out.println("Fruit name is " + banana.fruitName);
                // invoking the method seeds() on the object banana
                banana.seeds();
 }
 } 

Output: Compilation Error

 /MainClass.java:18: error: seeds() in Banana cannot override seeds() in Fruit
                void seeds()
                     ^ 

  attempting to assign weaker access privileges; was public

1 error

Explanation: The method seeds() has the public access specifier in the parent class, whereas, in the child class, seeds() has the default access specifier, which is weaker than the public access specifier. Thus, we are reducing the visibility of the method seeds(). Hence, we get the compilation error on the execution of the above program.

Types of Inheritance in Java

There are five types of inheritance in Java.

1) Single Inheritance

Inheritance Program in Java

In the above diagram, class Y is acquiring the properties of class X. Therefore, class X is the parent class, and class Y is the child class.  The following Java program also demonstrates the same.

 // X is the parent class
 class X
 { 
 void foo()
 {
     System.out.println("In the method foo ... ");
 } 
 }
 // Y is the child class
 class Y extends X
 { 
 void zoo()
 {
     System.out.println("In the method zoo ... ");
 } 
 }
 public class SingleInheritance
 { 
 // driver method
 public static void main(String argvs[])
 { 
     // creating an object of class Y
     Y y=new Y();
     // class Y has herited the method foo()
     y.foo(); 
     y.zoo(); 
 }
 } 

Output:

 In the method foo ...
 In the method zoo ... 

2) Multi-level Inheritance

Inheritance Program in Java

Multi-level inheritance is the extension of the single inheritance. In the above diagram, class Y is acquiring the properties of class X, and class Z is inheriting properties from class Y. Thus, class Y is the child class as it is inheriting properties from class X. Class Y is also the parent class as class Z is acquiring the properties of class Y. Consider the following example.

 // X is the parent class
 class X
 { 
 void foo()
 {
     System.out.println("In the method foo ... ");
 } 
 }
 // Y is the child class
 class Y extends X
 { 
 void zoo()
 {
     System.out.println("In the method zoo ... ");
 } 
 }
 // Here, class Y act as the parent class.
 // class Z is the child class of class Y.
 class Z extends Y
 { 
 void coo()
 {
     System.out.println("In the method coo ... ");
 } 
 }
 public class MultilevelInheritanceExample
 { 
 // driver method
 public static void main(String argvs[])
 { 
     // creating an object of class Z
     Z z=new Z();
     // class Z has herited the methods foo() and zoo()
     z.foo(); 
     z.zoo();
     z.coo();
 }
 } 

Output:

 In the method foo ...
 In the method zoo ...
 In the method coo ... 

3) Hierarchical Inheritance

Inheritance Program in Java

In hierarchical inheritance, one parent class has more than one child. In the given diagram, class Y and class Z are inheriting properties from class X. The following example illustrates the same.

 // X is the parent class
 class X
 { 
 void foo()
 {
     System.out.println("In the method foo ... ");
 }
 void zoo()
 {
     System.out.println("In the method zoo ... ");
 }
 }
 // Y is the child class of class X
 class Y extends X
 { 
 }
 // Z is the child class of class X
 class Z extends X
 { 
 }
 public class HierarchicalInheritanceExample
 { 
 // driver method
 public static void main(String argvs[])
 { 
     // creating an object of class Y
     Y y=new Y();
     // creating an object of class Z
     Z z=new Z();
     // class Y has herited the methods foo() and zoo()
     y.foo(); 
     y.zoo();
     // class Z has herited the methods foo() and zoo()
     z.foo(); 
     z.zoo();
 }
 } 

Output:

 In the method foo ...
 In the method zoo ...
 In the method foo ...
 In the method zoo ... 

4) Multiple Inheritance

Inheritance Program in Java

The opposite of multiple inheritance is hierarchical inheritance. In hierarchical inheritance, one child class has more than one parent. Note that multiple inheritance is not supported in Java. To understand the reason behind it, consider the following example.

Filename: MultipleInheritanceExample.Java

 // X is the parent class
 class X
 { 
 void foo()
 {
     System.out.println("In the method foo ... ");
 }
 }
 // Y is also the parent class
 class Y
 { 
  void foo()
 {
     System.out.println("In the method zoo ... ");
 }
 }
 // Z is the child class of class X and Y
 class Z extends X, Y
 { 
 }
 public class MultipleInheritanceExample
 { 
 // driver method
 public static void main(String argvs[])
 {     
     // creating an object of class Z
     Z z=new Z();
     // class Z has herited the methods foo() of class X and foo() class Y
     z.foo(); 
 }
 } 

Output: Compilation Error

Explanation: Class Z is the child class of class X and class Y. Also, the parent classes X and Y contain the method foo() of the same signature. Therefore, the child class Z inherits both the methods foo() mentioned in the classes X and Y. This leads to a dilemma when the method z.foo() is executed because it is not clear whether z.foo() invoking the method foo() of class X or of the class Y. Therefore, to completely eliminate this scenario, Java never supports multiple inheritance.

5) Hybrid Inheritance

Inheritance Program in Java

The Hybrid inheritance is the mixture of multiple and hierarchical inheritance. The upper part, where class Y and class Z are the children of class X, represents hierarchical inheritance, whereas the lower part, where the class XYZ is acquiring the properties of class Y and class Z, represents multi-level inheritance. Since multi-level inheritance is part of the hybrid inheritance, therefore Java does not support hybrid inheritance.



ADVERTISEMENT
ADVERTISEMENT