Firstable, interfaces structures provide interface to classes implemented for communicating outside world. Easy example would be a television. Television is a class and buttons on it are interfaces.
adv of using interfaces:
1-Java does not support multiple inheritance. If we want to add two different methods from different classes we cannot (extend ClassA,ClassB) is not possible implements A,B no problem.
2-The other adv is a security and flexibility An example can be given to be more specific
if we want that some of methods of the class are not reachable how can we do that?
polymorphism + interface we can do that
if we do not want walk and bark methods should be unreachable
abstract class Animal {
String name;
int age;
public Animal(String name, int age) {
super();
this.name = name;
this.age = age;
}
}
class Dog extends Animal implements Run {
public Dog(String name, int age) {
super(name, age);
// TODO Auto-generated constructor stub
}
@Override
public void run() {
// TODO Auto-generated method stub
}
public void bark() {
}
}
class Cat extends Animal implements Climb {
public Cat(String name, int age) {
super(name, age);
}
@Override
public void climb() {
// TODO Auto-generated method stub
}
public void walk() {
}
}
public class Main {
public static void main(String[] args) {
// if we want that some of methods of the class are not reachable how
// can we do that?
// polymorphism + interface we can do that
// for example if we do not want walk and bark methods should be
// unreachable
Climb cat = new Cat("boncuk", 5);
Run dog = new Dog("karabas", 7);
// see we cannot reach the method walk() or bark()
dog.walk(); // will give an error. since there is no such a method in the interface.
}
}}
enter code here