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:
- To differentiate between instance variables and method parameters with the same name.
- To call one constructor from another constructor in the same class.
- To return the current object from a method.
- 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 {
}
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 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