+ 5
Is that possible to create an object of interface class in java?
8 ответов
+ 3
No, interfaces are just abstractions of how the classes that implement them should be.
You can implement a class from the interface and create an instance of that class.
+ 2
yes it possible to create an object for an interface please refer inner classes in javatpoint
+ 1
You can declare variables as object references that use an interface rather than a class type.
Any instance of any class that implements the declared interface can be referred to by such a variable.
When you call a method through one of these references, the correct version will be called based on the actual instance of the interface being referred to.
+ 1
no but you can create references of interfaces which can hold the objects of the classes implementing that interface
+ 1
interfaces in java cannot be instantiated. you need an implementing class (a class that implements all the abstract methods that is in the interface).
+ 1
What is Interface in Java with Exam
What is an Interface?
An interface is just like Java Class, but it only has static constants and abstract method. Java uses Interface to implement multiple inheritance. A Java class can implement multiple Java Interfaces. All methods in an interface are implicitly public and abstract.
Syntax for Declaring Interface
interface {
//methods
}
To use an interface in your class, append the keyword "implements" after your class name followed by the interface name.
Example for Implementing Interface
class Dog implements Pet
interface RidableAnimal extends Animal, Vehicle
Please be patient. The Video will load in some time. If you still face issue viewing video click here
Why is an Interface required?
To understand the concept of Java Interface better, let see an example. The class "Media Player" has two subclasses: CD player and DVD player. Each having its unique implementation method to play music.
Another class "Combo drive" is inheriting both CD and DVD (see image below). Which play method should it inherit? This may cause serious design issues. And hence, Java does not allow multiple inheritance.
Now let's take another example of Dog.
Suppose you have a requirement where class "dog" inheriting class "animal" and "Pet" (see image below). But you cannot extend two classes in Java. So what would you do? The solution is Interface.
The rulebook for interface says,
An interface is 100% abstract class and has only abstract methods.
Class can implement any number of interfaces.
Class Dog can extend to class "Animal" and implement interface as "Pet".
Java Interface Example:
Step 1) Copy following code into an editor.
interface Pet{
public void test();
}
class Dog implements Pet{
public void test(){
System.out.println("Interface Method Implemented");
}
public static void main(String args[]){
Pet p = new Dog();
p.test();
}
}
Step 2) Save , Compile & Run the code. Observe the Output.
Read More: http://careerfund
0
nmhbd@azcml.....kkim
0
No.