This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Thursday, March 9, 2023

What is the use of this keyword? How is multiple inheritances achieved in java? Give example.

 In Java, the this keyword is a reference variable that refers to the current object instance in which the code is being executed. It is commonly used in class methods and constructors to refer to the instance variables and methods of the current object.

Some common uses of the this keyword in Java include:

  1. To differentiate between instance variables and method parameters with the same name.
  2. To call one constructor from another constructor in the same class.
  3. To return the current object from a method.
  4. To pass the current object as a parameter to another method.

In Java, multiple inheritances is achieved using interfaces. An interface is a collection of abstract methods and constants that can be implemented by any class. A class can implement multiple interfaces, which allows it to inherit the abstract methods and constants from all the implemented interfaces.

Here is an example of multiple inheritances in Java using interfaces:

interface A {

   public void methodA();
}
interface B {
   public void methodB();
}
class MyClass implements A, B {
   public void methodA() {
      System.out.println("Method A");
   }
   public void methodB() {
      System.out.println("Method B");
   }
}
public class Main {
   public static void main(String[] args) {
      MyClass obj = new MyClass();
      obj.methodA();
      obj.methodB();
   }
}

In this example, we define two interfaces A and B with their respective methods. We then define a class MyClass that implements both interfaces A and B. The MyClass class must implement the methods of both interfaces to be considered as fully implementing them. Finally, we create an object of MyClass and call its methodA() and methodB() methods. The output of the program will be:

Method A
Method B

which shows that the methods of both interfaces are successfully implemented by the MyClass class.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget