9.1 Interface
Hello everyone, in this video we will start talking about interface. So, the interfaces allow us to create a collection of methods that will have to be used when a class will implement the interface in question, roughly at the time we will therefore implement an interface in our class we will conclude a kind of contract between the class and the interface we have implemented in where we will have to take all the methods found in the interface and therefore place it in the class we have implemented the interface. So we will make an example to better understand. We will now create an interface to define the behaviour of a phone. To select "Class " select interface. So by convention, we normally type "I" capital letter as first letter. Now, in this Interface we want to define only the methods. So, the first method will be. Void Turn On Next, void Dial Phone int Phone number. Then, void answer And after Boolean Phone Call Int Phone Number. And Boolean Ring So it’s a simple interface. Again, all we’ve done here is to have a class implement the interface and use those methods. So, we don’t write code in the interface as such. We always have to write it in a class, which we will see. We are going to create a fixed phone class and we are going to implement the interface with the keyword "implements" So I am going to create two private variables Now, to use the interface methods We do as to do the constructor So, ALt + Insert then choose "Implement Methods". For our first method. We will display Writing. The office phone does not have a power button. We will display for the dial. For "answer", we will first check to see if it sounds good. So we’re going to do a if Parentheses ring inside We post answer to office phone. We’re going to put ring to false. For phone call, we will check if the phone number is equal to my phone number, if yes Then sounds equal true. Otherwise sounds equal false. And return sounds For the last one we just return "rings" Now, what we’re going to do is go to the "Main" class and write an instance of the fixed phone class. So write ITéléphone. As variable name tims phone tims phone is equal new Fixed Phone. 1 2 3 4 5 6. Now, I have a problem here because we didn’t make the builder. So we’re in the Landline class. And we’re going to declare the builder. Then, we’re going to go back to our main class and write tims dot turn on phone call. We can’t instantiate the interface, for example. If I do like that. 1 2 3 4 5 6. And as we can see, we have a mistake Now, we will launch our program to check if it works well And as we can see, we have our results. That’s all for this video I’ll tell you next time.