Given that interfaces are also used to help hide information, giving the user only a subset of the possible methods they are allowed to use, and, let's say, I have a Person class and interface IPerson.
Now in main, I'm allowed to do
IPerson testy = new Person();
or
Person testy = new Person();
So really I'm not restricted from using Person still. So how does the
interface truly hide data?
Aryan Kumar
04-Jul-2023No, the purpose of an interface is not to hide information. The purpose of an interface is to specify a contract between different classes. This contract defines the methods that a class must implement in order to be considered an implementation of the interface.
An interface can be used to hide information in some cases. For example, if an interface defines a method with no implementation, then the implementation of that method can be hidden from classes that implement the interface. However, this is not the primary purpose of an interface.
The primary purpose of an interface is to promote polymorphism. Polymorphism is the ability to use a variable of one type to refer to an object of another type. This can be useful for making code more flexible and reusable.
Here is an example of how an interface can be used to promote polymorphism:
Java
This code will first create an object of the
Bookclass and assign it to a variable of typeIPrintable. Then, it will call thePrint()method on the variable. ThePrint()method will be called on the object of theBookclass, and the text "This is a book" will be printed to the console.Next, the code will create an object of the
Articleclass and assign it to the variable of typeIPrintable. Then, it will call thePrint()method on the variable. ThePrint()method will be called on the object of theArticleclass, and the text "This is an article" will be printed to the console.As you can see, the
IPrintableinterface allows us to use a variable of typeIPrintableto refer to objects of different types. This is polymorphism in action.Vijay Shukla
12-Jun-2013Hey Jacob Rasel!
What if You dont have that Person class.
or