DEV Community

Cover image for Java Object Oriented Programming
Jeff Odhiambo
Jeff Odhiambo

Posted on

Java Object Oriented Programming

Object-oriented programming takes advantage of our perception of world. An object is an encapsulated completely-specified data aggregate containing attributes and behavior.

Data hiding protects the implementation from interference by other objects and defines approved interface. An object-oriented program is a growing and shrinking collection of objects that interact via messages.

You can send the same message to similar objects--the target decides how to implement or respond to a message at run-time. Objects with same characteristics are called instances of a class.
This article extends

  1. Java for Beginners: Introduction to Java
  2. Java for beginners: Installation of Java
  3. Java for beginners: Fundamentals of Java Kindly check on them to have a better understanding on this article.

Benefits of object-oriented programming include:

  • Troubleshooting is easy in OOP through modularity
  • Benefit of code re-usability through inheritance
  • Data redundancy is reduced
  • Code flexibility emphasis through polymorphism
  • Effective problem solving.

Java Classes

A class is essentially an abstract data type that provides a template from which objects are created. Class consists of a collection of data together with functions that operate on the data.
Data is referred to as data members and functions are referred to as member functions of a class. By declaring a class we create a new data type that is as powerful as any of the basic types.

class syntax

class <classname>{
    //body
}
Enter fullscreen mode Exit fullscreen mode

Example

class Student{
    //body
}
Enter fullscreen mode Exit fullscreen mode

Class data member

In a class, the members are by default hidden within the class and cannot be accessed from outside. We say that the members of a class are declared private by default. However, if we want to, we can declare members of a class to be public.
Syntax

class <classname>{
    <data_type> <variable_name>;
    //body
}
Enter fullscreen mode Exit fullscreen mode

Example

class Student{
    String student_name;
    int marks;
    Character grade;
    //body
}
Enter fullscreen mode Exit fullscreen mode

Class member functions (methods)

Member functions of a class are also referred to as methods. If we make the member data of our student class private, we should provide functions to access the data for setting, manipulating or printing.

Encapsulation and data hiding

Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class.
Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface.
Encapsulation gives maintainability, flexibility and extensibility to our code. Data encapsulation led to the important OOP concept of data hiding.

Java Variable Types

In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here:
<type> <identifier> = <value>; e.g
String name = "Jeff Odhiambo";
The type is one of Java's data types. The identifier is the name of the variable. To declare more than one variable of the specified type, use a comma-separated list.
Java supports the following types of variables:

1. Local variables

Local variables are declared in methods, constructors, or blocks. Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block. Access modifiers cannot be used for local variables. Local variables are visible only within the declared method, constructor or block. Local variables are implemented at stack level internally. There is no default value for local variables so local variables
should be declared and an initial value should be assigned before the first use.

2. Class (static) Variables

Class variables are shared by all the instances of the class. Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. Class methods are not tied to a specific object.
There would only be one copy of each class variable per class, regardless of how many objects are created from it. Static variables are created when the program starts and destroyed when the program stops. Static variables can be accessed by calling with the class name. Syntax ClassName.VariableName e.g Math.PI.

3. Constants (Final Variables)

Any variable either member variable or local variable (declared inside method or block) modified by final keyword is called final variable. Final variables are often declare with static keyword in java and treated as constant. A final variable can only be initialized once, either via an initializer or an assignment statement.
Class constants are final variables shared by all the instances of the class. Class variables, constants, and methods are used with class name, such as Math.pow(2,3), Math.PI.
To declare class variables, constants, and methods, use the static modifier.
When declaring class variables as public static final, then variables names (constants) are all in upper case. If the static variables are not public and final
the naming syntax is the same as instance and local variables.
Example

import java.io.*;
public class Employee{
    // salary variable is a private static variable
    private static double salary;
    // DEPARTMENT is a constant
    public static final String DEPARTMENT = "Development ";
    public static void main(String args[]){
        salary = 1000;
        System.out.println(DEPARTMENT+"average salary:"+salary);
    }
}
Enter fullscreen mode Exit fullscreen mode

4. Instance variables

Instance variables are declared in a class, but outside a method, constructor or any block. When a space is allocated for an object in the heap a slot for each instance variable value is created. Instance variables are created when an object is created with the use of the key word 'new' and destroyed when the object is destroyed.
Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object’s state that must be present throughout the class. Instance variables can be declared in class level before or after use. Access modifiers can be given for instance variables.

The instance variables are visible for all methods, constructors and block in the class. Normally it is recommended to make these variables private (access level). However visibility for sub classes can be given for these variables with the use of access modifiers.
Instance variables have default values. For numbers the default value is 0, for Booleans it is false and for object references it is null. Values can be assigned during the declaration or within the constructor.
Instance variables can be accessed directly by calling the variable name inside the class. However within static methods and different class ( when instance variables are given accessibility) the should be called using the fully qualified name . ObjectReference.VariableName.

Scope of Variables

The scope of instance and class variables is the entire class. They can be declared anywhere inside a class. They are global variables. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can be used.
E.g.
Scope of variable

Visibility Modifiers and Accessor Methods

By default, the class, variable, or data can be accessed by any function in the class in which they are declared. Visibility modifiers include:
Public - The class, data, or method is visible to any class in any package.
Private - The data or methods can be accessed only by the declaring class.
Protected

Accessor methods(Setters and Getters Methods)

The getter and setter accessor methods are used to read and modify private properties in a class. These methods are also called accessor methods.
The syntax for accessor methods is:

public class AccessorExample {
    private String attribute;
    public String getAttribute() {
        return attribute;
    }
    public void setAttribute(String attribute) {
        this.attribute = attribute;
    }
}
Enter fullscreen mode Exit fullscreen mode

Java this Keyword

The keyword this in Java refers to the current class instance. Within an instance method or a constructor, this is a reference to the current object. Therefore, this can be used inside any method to refer to the current object. You can refer to any member of the current object from within an instance method or a constructor by using this . The keyword can also be used to call overloaded constructors.

Using this to access a shadowed field

The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.
For example, the Point class was written like this

public class Point {
    public int x = 0;
    public int y = 0;
    //constructor
    public Point(int a, int b) {
        x = a;
        y = b;
    }
}
Enter fullscreen mode Exit fullscreen mode

but it could have been written like this:

public class Point {
    public int x = 0;
    public int y = 0;
    //constructor
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
Enter fullscreen mode Exit fullscreen mode

Each argument to the constructor shadows one of the object's fields — inside the constructor x is a local copy of the constructor's first argument. To refer to the Point field x , the constructor must use this.x .

Using this to call a Constructor from another constructor

From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. Here's another Rectangle class, with a different implementation from the one in the Objects section.

public class Rectangle {
    private int x, y;
    private int width, height;
    public Rectangle() {
        this(0, 0, 0, 0);
    }
    public Rectangle(int width, int height) {
        this(0, 0, width, height);
    }
    public Rectangle(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
}
Enter fullscreen mode Exit fullscreen mode

This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member variables. The constructors provide a default value for any member variable whose initial value is not provided by an argument.

Data encapsulation

Data encapsulation is a mechanism of bundling the data, and the functions that use them.
Example

public class Student {
    private String name;
    private String idNum;
    private int age;

    public int getAge() {
        return age;
    }
    public String getName() {
        return name;
    }
    public String getIdNum() {
        return idNum;
    }
    public void setAge(int newAge) {
        age = newAge;
    }
    public void setName(String newName) {
        name = newName;
    }
    public void setIdNum(String newId) {
        idNum = newId;
    }
}
Enter fullscreen mode Exit fullscreen mode

Encapsulation using “this” Example

public class Student{
    private String name;
    private String idNum;
    private int age;
    public int getAge(){
        return age;
    }
    public String getName(){
        return name;
    }
    public String getIdNum(){
        return idNum;
    }
    public void setAge( int age){
        this.age = age;
    }
    public void setName(String name){
        this.name = name;
    }
    public void setIdNum( String idNum){
        this.idNum = idNum;
    }
}
Enter fullscreen mode Exit fullscreen mode

Advantage of Encapsulation in Java and OOPS

Here are few advantages of using Encapsulation while writing code in Java or any Object oriented programming language:

  1. Encapsulated Code is more flexible and easy to change with new requirements.
  2. Encapsulation in Java makes unit testing easy.
  3. Encapsulation in Java allows you to control who can access what.
  4. Encapsulation also helps to write immutable class in Java which are a good choice in multi-threading environment.
  5. Encapsulation reduce coupling of modules and increase cohesion inside a module because all piece of one thing are encapsulated in one place.
  6. Encapsulation allows you to change one part of code without affecting other part of code.

Relationships among Classes

Association

Association is a relationship between two objects. Association represents a general binary relationship that describes an activity between two classes.
The association relationship is a way of describing that a class knows about and holds a reference to another class.
You may be aware of one-to-one, one-to-many, many-to-one, many-to-many all these words define an association between objects.

Aggregation

Aggregation is a relationship between two classes that is best described as a "has-a" and "whole/part" relationship.
Aggregation models the relationship like has-a, part-of, owns, and employed-by. When an object ‘has-a’ another object, then you have got an aggregation between them.
Direction between them specifies which object contains the other object. Aggregation is also called a “Has-a” relationship.
Example
There is an aggregation relationship between Student class and the Subject class:

public class Subject {
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}
public class Student {
    private Subject[] studyAreas = new Subject[10];
}
Enter fullscreen mode Exit fullscreen mode

Find more examples here

Composition

Composition is restricted aggregation. When an object contains the other object,i.e., if the contained object cannot exist without the existence of container object, then it is called composition.
Example: A class contains students. A student cannot exist without a class.
There exists composition between class and students.

Abstraction

Abstraction is specifying the framework and hiding the implementation level information. Concreteness will be built on top of the abstraction. It gives you a
blueprint to follow to while implementing the details. Abstraction reduces the complexity by hiding low level details.
Example: A wire frame model of a car.

Generalization

Generalization uses a “is-a” relationship from a specialization to the generalization class. Common structure and behavior are used from the specialization to the generalized class. At a very broader level you can understand this as inheritance. Why I take the term inheritance is, you can relate this term very well.
Example: Consider there exists a class named Person. A student is a person. A faculty is a person. Therefore here the relationship between student and person, similarly faculty and person is generalization.

Realization

Realization is a relationship between the blueprint class and the object containing its respective implementation level details. This object is said to
realize the blueprint class. In other words, you can understand this as the relationship between the interface and the implementing class.
Example: A particular model of a car ‘GTB Fiorano’ that implements the blueprint of a car realizes the abstraction.

Dependency

Change in structure or behavior of a class affects the other related class, then there is a dependency between those two classes. It need not be the same on the vice-
versa. When one class contains the other class this happens.
Example: Relationship between shape and circle is dependency.

Inheritance (developed from)

Inheritance models the “is-a” relationship between two classes. It is a mechanism where a new class is derived from an existing class.
In Java, classes may inherit or acquire the non private properties and methods of other classes. A class derived from another class is called a subclass, whereas
the class from which a subclass is derived is called a super class. A subclass can have only one super class, whereas a super class may have one or more sub classes.

Any class in java that does not extend any other class implicitly extends Object class. Therefore, the java.lang.Object class is always at the top of any Class inheritance hierarchy.
In Java, inheritance is used for two purposes:
1. Class inheritance - create a new class as an extension of another class, primarily for the purpose of code reuse. That is, the derived class inherits the public methods and public data of the base class. Java only allows a class to have one immediate base class,
i.e., single class inheritance. The keyword “extends” is used to derive a subclass from the superclass, as illustrated by the following syntax:
syntax

public class derived-class-name extends base-class-name {
// derived class methods extend and possibly override those of the base class
}
Enter fullscreen mode Exit fullscreen mode

example

class A{
//properties and methods of A
}
class B extends A {
}
Enter fullscreen mode Exit fullscreen mode

Class inheritance defines a is-a relationship between a superclass and its subclasses. Therefore inheritance is achieved at class level. We can therefore define inheritance in java as mechanism is used to build new classes from existing classes.
For example:

public class Animal{
}
public class Mammal extends Animal{
}
public class Reptile extends Animal{
}
public class Dog extends Mammal{
}
Enter fullscreen mode Exit fullscreen mode

In Object Oriented terms following are true:

  • Animal is the super class of Mammal class.
  • Animal is the super class of Reptile class.
  • Mammal and Reptile are sub classes of Animal class.
  • Dog is the subclass of both Mammal and Animal classes.

Now if we consider the IS-A relationship we can say:

  • Mammal IS-A Animal
  • Reptile IS-A Animal
  • Dog IS-A Mammal
  • Hence : Dog IS-A Animal as well With use of extends keyword the sub classes will be able to inherit all the properties of the super class except for the private properties of the super class. Below is a sample implementation of the Dog class:
public class Dog extends Mammal{
    public static void main(String args[]){
        Animal a = new Animal();
        Mammal m = new Mammal();
        Dog d = new Dog();
        System.out.println(m instanceof Animal);//Outputs true
        System.out.println(d instanceof Mammal); //Outputs true
        System.out.println(d instanceof Animal); //Outputs true
    }
}
Enter fullscreen mode Exit fullscreen mode

The Boolean instanceof operator is used to determine whether Mammal is actually an Animal, and dog is actually an Animal.

super keyword

‘super’ is used for pointing the super class instance. That is, it is a reference variable that is used to refer immediate parent class object.
The keyword super will therefore be used when referring to the super class of an object.

Uses of super Keyword

super is used to refer immediate parent class instance variable.
super() is used to invoke immediate parent class constructor.
super is used to invoke immediate parent class method.
Using the super keyword to call immediate parent class constructor
The syntax for calling a super class constructor is
super(); or super(parameter list);
NB: In a constructor, super MUST always be the first statement to appear:
Example:

class Vehicle{
    Vehicle(){
        System.out.println("Vehicle is created");
    }
    Void start(){
        System.out.println("Vehicle is starting...");
    }
}
class Bike extends Vehicle{
    Bike(){
        super();//will invoke parent class constructor
        System.out.println("Bike is created");
    }
    public static void main(String args[]){
        Bike b=new Bike();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Vehicle is created
Bike is created
Enter fullscreen mode Exit fullscreen mode

With super(), the super class no-argument constructor is called. With super(parameter list), the super class constructor with a matching parameter list is called. If accessing a method in super class, we use the syntax:
super.methodName( argument(s))
super.start();

Method Overriding

When a sub class defines a method that has same name signature and return type (or compatible with return type of super class method) it is called method overriding. In object oriented terms, overriding means to override the functionality of any existing method.
The benefit of overriding is: ability to define a behavior that's specific to the sub class type. Which means a subclass can implement a parent class method based on its requirement.
Consider the following example

class Animal{
    public void move(){
        System.out.println("Animals can move");
    }
}
class Dog extends Animal{
    public void move(){
        System.out.println("Dogs can walk and run");
    }
}
public class TestDog{
    public static void main(String args[]){
        Animal a = new Animal(); // Animal reference and object
        Animal b = new Dog(); // Animal reference but Dog object
        a.move();// runs the method in Animal class
        b.move();//Runs the method in Dog class
    }
}
Enter fullscreen mode Exit fullscreen mode

This would produce following result:

Animals can move
Dogs can walk and run
Enter fullscreen mode Exit fullscreen mode

In the above example you can see that the even though b is a type of Animal it runs the move method in the Dog class. The reason for this is : In compile time the check is made on the reference type. However in the runtime JVM figures out the object type and would run the method that belongs to that particular object.
Therefore in the above example, the program will compile properly since Animal class has the method move. Then at the runtime it runs the method specific for that object.
Consider the following example :

class Animal {
    public void move() {
        System.out.println("Animals can move");
    }
}
class Dog extends Animal {
    public void move() {
        System.out.println("Dogs can walk and run");
    }

    public void bark() {
        System.out.println("Dogs can bark");
    }
}
public class TestDog {
    public static void main(String args[]) {
        Animal a = new Animal(); // Animal reference and object
        Animal b = new Dog(); // Animal reference but Dog object

        a.move();// runs the method in Animal class
        b.move();//Runs the method in Dog class
        b.bark();
    }
}
Enter fullscreen mode Exit fullscreen mode

This would produce following result:

TestDog.java:30: cannot find symbol
symbol : method bark()
location: class Animal
b.bark();
  ^
Enter fullscreen mode Exit fullscreen mode

This program will throw a compile time error since b's reference type Animal doesn't have a method by the name of bark.

Using the super keyword to call overridden method

When invoking a super class version of an overridden method the super keyword is used.

class Animal{
    public void move(){
        System.out.println("Animals can move");
    }
}
class Dog extends Animal{
    public void move(){
        super.move(); // invokes the super class method
        System.out.println("Dogs can walk and run");
    }
}
public class TestDog{
    public static void main(String args[]){
        Animal b = new Dog(); // Animal reference but Dog object
        b.move(); //Runs the method in Dog class
    }
}
Enter fullscreen mode Exit fullscreen mode

This would produce following result:

Animals can move
Dogs can walk and run
Enter fullscreen mode Exit fullscreen mode

Rules for method overriding:

  • The argument list should be exactly the same as that of the overridden method.
  • The return type should be the same or a sub type of the return type declared in the original overridden method in the super class.
  • The access level cannot be more restrictive than the overridden method's access level. For example: if the super class method is declared public then the overridding method in the sub class cannot be either private or protected.
  • Instance methods can be overridden only if they are inherited by the subclass.
  • A method declared final cannot be overridden.
  • A method declared static cannot be overridden but can be re-declared.
  • If a method cannot be inherited then it cannot be overridden.
  • A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.
  • A subclass in a different package can only override the non-final methods declared public or protected.
  • An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method.
  • Constructors cannot be overridden.

Data abstraction

Abstraction is the concept of object-oriented programming that “shows” only essential attributes and “hides” unnecessary information. The main purpose of abstraction is hiding the unnecessary details from the users. The implementation details is hidded from the user. Abstraction is achieved using either abstract classes or interfaces.

Class Abstraction

Class abstraction means to separate class implementation from the use of the class. The creator of the class provides a description of the class and let the user know how the class can be used. The user of the class does not need to know how the class is implemented. The detail of implementation is encapsulated and hidden from the user.

Abstract Classes and Abstract Methods

An abstract class is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class). An abstract class leaves one or more method implementations unspecified by declaring one or more methods abstract. An abstract can only be used as a super class for other classes that
extend the abstract class. Abstract classes are declared with the abstract keyword. Abstract classes are used to provide a template or design for concrete subclasses down the inheritance tree.
Abstract methods are methods with no body specification (implementation).
Abstract methods can only be used in an abstract class, and it does not have a body. I.e Abstract method would have no definition, and its signature is followed by a semicolon, not curly braces. The body is provided by the subclass (inherited from).
The abstract keyword is a non-access modifier, used for classes and methods. The abstract keyword is used to declare a class or a method as abstract. An abstract method consists of a method signature, but no method body.
Example

abstract class Shape {
    public String color;

    public Shape() {
    }

    public void setColor(String c) {
        color = c;
    }

    public String getColor() {
        return color;
    }

    abstract public double area();
}
Enter fullscreen mode Exit fullscreen mode

Note that If a class has at least one abstract method, the class must be declared as abstract.
A subclass is therefore required to override the abstract method and provide an implementation. Subclasses must provide the method statements for their particular meaning. If the method was one provided by the superclass, it would require overriding in each subclass. Hence, an abstract class is incomplete and cannot be instantiated, but can be used as a base class.
The abstract class guarantees that each shape will have the same set of basic properties. We declare this class abstract because there is no such thing as a generic shape. There can only be concrete shapes such as squares, circles, triangles etc.

public class Point extends Shape {
    static int x, y;

    public Point() {
        x = 0;
        y = 0;
    }

    public double area() {
        return 0;
    }

    public double perimeter() {
        return 0;
    }

    public static void print() {
        System.out.println("point: " + x + "," + y);
    }

    public static void main(String args[]) {
        Point p = new Point();
        p.print();
    }
}
Enter fullscreen mode Exit fullscreen mode

Points to Remember

  • An abstract class must be declared with an abstract keyword.
  • It can have abstract and non-abstract methods.
  • It cannot be instantiated.
  • It can have constructors and static methods also.
  • It can have final methods which will force the subclass not to change the body of the method. ##Interfaces An interface in Java is a blueprint of a class. It consists of static constants and abstract methods. In Java, an interface is a mechanism to achieve abstraction. There can be only abstract methods in a Java interface. No need to include keyword abstract when declaring abstract methods in in interface. Just like an abstract class, an interface cannot be instantiated. You can declare an interface in its own file like a class. In such a case, File name must be the same as the class name. Java Interface also represents the IS-A relationship. ###Declaring Interfaces The interface keyword is used to declare an interface. Syntax:
interface <interface_name>{
// declare constant fields
// declare abstract methods
}
Enter fullscreen mode Exit fullscreen mode

Example:

/* File name : Animal.java */
interface Animal {
    public void eat();
    public void travel();}
}
Enter fullscreen mode Exit fullscreen mode

Implementing an interface

Class inheritance in java uses the keyword extends. To access the interface methods, the interface must be "implemented" (inherited) by another class using the implements keyword (instead of extends). During implementation the body of each interface method is provided by the "implementing" class:
Syntax:

public class class-name implements interface-name {
// class provides an implementation for the methods
// as specified by the interface
}
Enter fullscreen mode Exit fullscreen mode

Example:

interface Animal {
    public void makeSound(); // interface method (does not have a body)

    public void sleep(); // interface method (does not have a body)}

    //Donkey "implements" the Animal interface
    class Donkey implements Animal {
        public void makeSound() {
            // The body of animalSound() is provided here
            System.out.println("The donkey says: hee hoo");
        }

        public void sleep() {
            // The body of sleep() is provided here
            System.out.println("Zzz");
        }
    }

    public class DonkeyImpl {
        public static void main(String[] args) {
            Donkey dnk = new Donkey();
            // Create a Donkey object
            dnk.makeSound();
            dnk.sleep();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

  • It is used to achieve abstraction.
  • By interface, we can support the functionality of multiple inheritance.
  • It can be used to achieve loose coupling. Interfaces are preferred to classes because they help us to to achieve abstraction as well as multiple inheritance in Java.

Extending Interfaces

An interface can extend another interface in the same way that a class can extend another class. The extends keyword is used to extend an interface, and the child
interface inherits the methods of the parent interface.
Example

// Filename: Sports.java
public interface Sports {
    public void setHomeTeam(String name);
    public void setVisitingTeam(String name);
}
// Filename: Football.java
public interface Football extends Sports {
    public void homeTeamScored(int points);
    public void visitingTeamScored(int points);
    public void endOfQuarter(int quarter);
}
// Filename: Hockey.java
public interface Hockey extends Sports {
    public void homeGoalScored();

    public void visitingGoalScored();

    public void endOfPeriod(int period);

    public void overtimePeriod(int ot);
}
Enter fullscreen mode Exit fullscreen mode

Multiple Class Inheritance in Java

A class can extends ONLY one parent class using the extends keyword. Multiple class inheritance is not allowed.
Class inheritance inheritance in java has the following limitations.

  • A subclass cannot inherit private members of its super class.
  • A subclass can have only one super class.
  • Constructor and initializer blocks cannot be inherited by a subclass. Interfaces are not classes, thus you are allowed to inherit one or more interfaces. Multiple inheritance by interface occurs if a class implements multiple interfaces or also if an interface itself extends multiple interfaces.

Extending Multiple Interfaces

To achieve multiple inheritance, java allows you to implement more than one parent interfaces by declaring them in a comma-separated list. E.g.
public interface Hockey extends Sports, Event
Note that an interface can extend more than one parent interface
interface

Difference between Abstraction and Encapsulation

abstraction

Difference between Abstract Class and Interface

interfaces
In the next article we will discuss Polymorphism in java in depth.

Thanks for taking your time to read this article.

Top comments (0)