Thursday, August 8, 2024

Interface

Interface :

An interface in Java is similar to a class but contains only abstract methods (methods without a body) and constants.

 

                              is similar to class

               //  class contains  inst var +   inst methods

 

               //  Interface also contains some const  var   and some methods

 

               //  Interface contains only abstr methods  (does not have any method body)

               //  abstr method-   is incomplete method

               //   we dont define any method body

These methods must be implemented by any class that implements the interface.

Constants: An interface can contain constants, which are implicitly public, static, and final.

No Method Body: Interfaces cannot contain concrete methods (methods with a body)

·  Access Modifiers: Methods in an interface are implicitly public and must be implemented as public in the implementing class.

·  No Instance Variables: Interfaces cannot have instance variables, but they can have constants.

 

·        interface   is predefined k/w in java

·        Interface can be used to define interface

 

syntax :

               interface  someName

               {

                             

               }

 

ex1:      

package InterfaceBasics;

 

public interface I1 {

    // Instance variable name = "Ramu";

    String name = "Ramu";

    // This is implicitly public, static, and final.

 

    // Define a constant pi = 3.14f;

    public static final float pi = 3.14f;

 

    // only Abstract methods

// define Abstract methods M1(), M2()

    abstract void M1(); // Abstract method - must be implemented by a class that implements this interface.

 

    void M2(); // This will also be treated as an abstract method even without the 'abstract' keyword.

    // It's not compulsory to write the 'abstract' keyword for methods in an interface.

 

    // Define M3 with body ?? - Not allowed in this context

    // The following would cause a compile-time error:

    // void M3() {

    //     System.out.println("Non-abstract method");

    // }

    // Compile-time error: Abstract methods do not specify a body

}

Implementing Interface I1 Methods in a Class:

·        To implement the methods defined in an interface, we use the implements keyword in Java.

·        implements is predefined k/w in java

·        implements k/w can be used to implement (or) define method with body  with  some lines of code

package InterfaceBasics;

 

public class A implements I1 //CE: The type A must implement the inherited abstract method I1.M1()

{  // Implements I1 interface methods  //  name, pi , M1, M2()

 

 

               // implement M1() - Defining method with body

 

               public void M1()

               {

                              System.out.println("implementing M1 ");

               }

 

              

               // implement M2()

//            public void M2()

//            {

//                           System.out.println("implementing M2 ");

//            }

               // Click Add unimplemented Methods -The type A must implement the inherited abstract method I1.M2()

              

               @Override

               public void M2()

               {

                              System.out.println("implementing M2 ");                            

               }

 

 

}

 

 

package InterfaceBasics;

 

public class TestInterface

{

 

               public static void main(String[] args) {

                              // Create obje for class-A

                              A aref = new A();

                              // display a name

                              System.out.println("aref name="+ aref.name);// Ramu

                              // 

                              // call M1()

                              aref.M1();

                              // call M2()

                              aref.M2();

 

                              // change interface variable values name, pi

 

//                                          aref.name = "Osmania"; // final var - cannot be change as it is const

                              //   we cannot change final var value..

                              // The final field I1.College cannot be assigned

//                                                                                       aref.pi =  5.2f;   

                              // The final field I1.College cannot be assigned

 

                              // Access interface var name, pi using interface name

                              //Syntax :  Interfacename.var

                              System.out.println("I1 name ="+ I1.name);

                              System.out.println("I1 Pi ="+ I1.pi);

 

                              // Can we call M1() using I1?

//                                          I1.M1();// CE:Cannot make a static reference to the non-static method M1() from the type I1

 

 

               }

}

o/p:

aref name=Ramu

implementing M1

implementing M2

I1 name =Ramu

I1 Pi =3.14

 

ex2:

 

package InterfaceBasics;

 

public interface car {

 

                //  only abstr method

                              //      some functions of car

                              // define abst method -startCar()

                              abstract void startCar();

                             

                              // define abst method -stopcar()

                              abstract void stopCar();                

 

}

 

 

 

 

package InterfaceBasics;

 

public class MaruthiCar implements car

{  // implementing car interface methods

 

               //  implement startCar()

                 public void startCar()

                 {           

                              System.out.println("start car-insert key and turn to right side");

                 }

                              //  implement stopCar()

                 public void stopCar()

                 {

                              System.out.println("stop car - turn keys to left side");

                 }

              

}

 

 

---------------------

 

package InterfaceBasics;

 

public class BMW implements car

{

               // implements  car

               //  implement startCar()

               public void startCar()

               {

                              System.out.println("start car-Press start button");

 

               }             

               //  implement stopcar()

               public void stopCar()

               {

                              System.out.println("stop car - Press stop button");

               }

 

}

 

package InterfaceBasics;

 

public class Tesla implements  car

{

               //implements  car

               //implements startCar()

 

               public void startCar()

               {

                              System.out.println("start car-AI/  voice commands ");

               }

                              //implements stopCar()

                                                            // if we dont write,  it throws - we must define all abstr methods

               public void stopCar()

               {

                              System.out.println("stop car - voice command ");

               }

 

}

 

----------------------

 

package InterfaceBasics;

 

public class TestCar

{

 

               public static void main(String[] args) {

 

                              // create obj of maruthicar class

                              MaruthiCar mcar = new MaruthiCar();

                             

                              // call  startCar();

                              mcar.startCar();

                             

                              // create obj for BMW- class

                              BMW bmwref = new BMW();

                             

                              // call startCar();

                              bmwref.startCar();

                             

                              //HW create obj  for Teslacar class and call the methods

                             

                             

 

               }

 

}

 

o/p:

start car-insert key and turn to right side

start car-Press start button

HW  Define interface -printer

    printing(),  changingInk(); --> abstract methods

 

 define classes HPPrinter, DellPrinter which implements 'printer' interface methods

 

Hw Define interface - DB,

   Define abstr methods -  connectToDataBase()  disconnectFromDataBase()

  Implement above methods in classes (Oracle, MySql, SqlServer)

 

 

Class Implementing Multiple Interfaces:

In Java, a class can implement multiple interfaces.

 

class A implements I1

 

class A implements I1, I2

 

class A implements I1, I2, I3.....etc

 

/// In class A , we must implement/ provide method body to the I1 interface methods

                                                                           // and I2 interface methods else it throws CE

                             

 

 

package TestMultipleInterfaces;

 

package InterfaceBasics;

 

public interface I1

{

               //   Abstr Methods only 

               //abstract key word is optional

///  even if we dont write abstract k/w before method name, by default abst k/w is added

               // Define abstr method -M1()

                              abstract void M1();

              

}

 

 

------------------

package InterfaceBasics;

 

public interface I2

{

               // Define abstr method -M2()

                              abstract void M2();

              

}

 

 

--------------

 

package InterfaceBasics;

// I1 , I2

public class TestMultipleInterfaces implements I1,I2

{                                                                                                           //  M1()  , M2()

               ///  implements I1,I2

               // The type TestMultipleInterfaces must implement the inherited abstract method I1.M1()

 

                              // implement M1()

                              public void M1()

                              {              // method from I1 inetrface

                             

                                             System.out.println("calling M1()");                         

                              }

                              // implement M2()

                                                             // method from I2 interface

                              public void M2()

                              {

                                             System.out.println("calling M2()");

                              }

 

                              public static void main(String[] args)

                              {

                                                           

                                             // create obj for the lcass-TestMultipleInterfaces

                                             TestMultipleInterfaces tref = new TestMultipleInterfaces();

                                                                          

                                             // call M1()

                                             tref.M1();

                                             // call M2()

                                             tref.M2();

 

                              }

 

 

 

}

 

 

o/p:

calling M1()

calling M2()

 

Inheritance with Interfaces and Classes:

In Java, interfaces can extend other interfaces, just like how classes can extend other classes

class A

{

              

}

 

class B extends A //

{

              

}

 

 Interface I1

{

 

}

 

 Interface I2 extends I1

{

 

}

·        interfaces can inherit methods from other interfaces, and classes can implement those interfaces.

-------------------

 

package TestMultipleInterfaces;

 

 

//  one interface extends another interface

package InterfaceBasics;

 

public interface I3 {

               // Define  name = "Ramu";

               String name = "Ramu";

              

                              // Define abst method -M1()

               abstract void M1();

 

 

}

 

package InterfaceBasics;

 

public interface I4 extends I3

{

//  parent interface -  I3

               // child interface - I4

              

                                                                                          //  gets parent interface i.e I3 Variables  +  Methods into child interface I4

                                                                                                         // ie. name, M1() into child interface- i.e I4

              

               //Define var  college = "Jntu";

               String colege = "Jntu";

              

               // Define abst method -M2()      

               abstract void M2();

 

}

 

 

 

package InterfaceBasics;

 

// I3 , I4 -child

public class TestInheritanceInterface implements I4

{

                //implements  I4

 

                              // implementing M1()    

                              public void M1()

                              {

                                             System.out.println("implementing M1 Method");             

                              }

                             

                              // implementing  M2()

                              public void M2()

                              {

                                             System.out.println("implementing M2 Method");

                              }

                             

                              public static void main(String[] args) {

                                             // create obj for class- TestInheritanceInterface

                                             TestInheritanceInterface tref = new TestInheritanceInterface();

                                             // call M1()

                                             tref.M1();

                                            

                                             // HW Call M2();

                                            

                              }

 

 

}

 

 

o/p:

impementing M1 Method

Key Points:

1.     Interface Inheritance:

    • I4 extends I3, which means that I4 inherits all methods and variables from I3.
    • Any class that implements I4 must provide concrete implementations for all abstract methods in both I4 and I3.

 

 

FAQ : Can Interface implement another interface ?

No, an interface cannot implement another interface. Implementing in Java means providing a concrete implementation (method body) for abstract methods. Since interfaces are meant to declare abstract methods without any implementation, they cannot implement other interfaces.

package TestMultipleInterfaces;

//  one interface extends another interface

interface I5

{

               String name = "Ramu";

               void M1();//  Abstra methods

}

 

interface I6

{ // implements I5  //Error:  invalid  Syntax error on token "implements", permits expected

               String college = "Jntu";

               void M2();

               // implements M1()        

              

}

 

 

which one are valid/invalid ?

 

class B extends A //  --> valid

{

 

}

inertface I1 extends I2 // --> valid

{

 

}

class A implements I1  // --> valid

{

 

}

class B implements I1, I2 // -->  valid

{

 

}

 

interface I1 implements I2  // -->  invalid

{

 

}

 

-----------------------

abstact class with variables:

----------------------------

 

package AbstractClassBasics;

 

public abstract class A  // abstract class

{

                // var name  = "Abs val";

              

}

 

 

-------------

package AbstractClassBasics;

 

public class B extends A

{                                                               // // var

                                                            //                             String name  = "Abs val";

              

               //  implement abstr method M1  from class -A

 

              

                              System.out.println("M1");

              

  // implement abstr method M2  from class -A

                

                             

              

               public static void main(String[] args) {

                                                           

//                           Create obj for class - B

                             

//                           System.out.println("accessing parent class - abstact class var val="+ name);

                               // Cannot make a static reference to the non-static field name

          // b1 name

 

                               

//   can we change abstr class var value ?  name = "Raju";

 

 

                               

                             

                              }

 

}

 

o/p:

 

FAQ: Difference Between Abstract Class and Interface

1. Abstract Class: Can contain both abstract methods (without a body) and non-abstract methods (with a body).

Interface: Contains only abstract methods (without a body) but not non abstract methods

 

2. Abstract Class: Defined using the abstract keyword.

Interface: Defined using the interface keyword.

 

3. Abstract Class: Can have final, non-final, static, and non-static variables.

Interface: Variables are implicitly public, static, and final.

 

4. Abstract Class: Can be extended by a subclass using the extends keyword.

Interface: Can be implemented by a class using the implements keyword.

 

5. A Java abstract class can have class members like public,  private, protected, etc.

Interface: All members (methods and variables) are public by default. No other access modifier is allowed.

 

6. when we want to implement some methods and some methods we dont want to implement then we will go for abstract class

                             

// When we want to implement all methods in child class - then we will go for interface

Feature

Abstract Class

Interface

 

Methods

Can contain both abstract and non-abstract methods.

Contains only abstract methods (and optionally default/static methods in Java 8+).

 

Keywords

Defined using the abstract keyword.

Defined using the interface keyword.

 

Variables

Can have final, non-final, static, and non-static variables.

Variables are implicitly public, static, and final.

 

Inheritance

Can be extended by a subclass using the extends keyword.

Can be implemented by a class using the implements keyword.

 

Access Modifiers

Members can have different access levels (private, protected, public).

All members are public by default. No other access modifier is allowed.

 

Use Case

Used when a base class has some common functionality that subclasses can inherit and/or override.

Used to define a contract that implementing classes must fully adhere to, without providing method implementation.

 

Implementation

Allows partial implementation, meaning some methods can be implemented, and others left for subclasses.

Requires that all methods must be implemented by the class that implements the interface.

 

Constructor

Can have constructors to initialize class fields.

Cannot have constructors as they only define behavior, not state.

 

*************************************************

package TestMultipleInterfacces;

abstract class Ab1

{

               //   abstract methods +   non abst Methods

               abstract void M1(); //  abstract k.w is compulsory

               void M2()

               {

                              System.out.println("Caling M2");

               }

}

interface I7

{

               //  only  abstract method only  but not non abstract methods

                void M3();// ABSTRACT K/w is not compulsory even if we dont write abstract k.w, it will be added by default

}

public class DiffAbstactClassInterface {

               public static void main(String[] args) {

                              // Can we create obj for the abstract class ?

//                           Ab1  a1ref=  new Ab1();// Error : Cannot instantiate the type Ab1

                              // We cannot create object for abstract class

                             

                              // We cannot create obj for Interface

//                           I7  i7ref =  new I7();// Error :

//                           Cannot instantiate the type I7

                              // We cannot create obj for interface also

                             

//            note:     after new k/w,  usually we see classname only

//                           ex:   new A();

                             

//                           When to

//                           when we want to implement some methods and some methods we dont want to implement then we will go for abstract class

                              // When we want to implement all methods in child class - then we will go for interface

                             

                              // In abstract class, abstract k/w  is compulsory for abstract Methods

                                             void M3(); //  here abstract k/w is compulsory

                              // In interface ,  abstract k/w  is not compulsory for abstract Methods

               void M4(); //   default it adds abstract k./w for abstract methods in interface

or     

         abstract void M4();

                             

               }

}

No comments:

Post a Comment

git commands MCQ

 Here are some multiple-choice questions (MCQs) on Git commands relevant for Selenium: 1. Which Git command is used to clone a remote reposi...