How does a class extension or Interface work?

Asked
Active3 hr before
Viewed126 times

10 Answers

class
90%

An interface can extend another interface, in a similar way as a class can extend another class.,An interface can extend another interface in the same way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface.,The interface keyword is used to declare an interface. Here is a simple example to declare an interface −,The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.

Following is an example of an interface −

/* File name : NameOfInterface.java */
import java.lang.*;
// Any number of import statements

public interface NameOfInterface {
   // Any number of final, static fields
   // Any number of abstract method declarations\
}
load more v
88%

An extension method will never be called if it has the same signature as a method defined in the type.,Extension methods and Curried Delegates,The MethodB extension method is never called because its name and signature exactly match methods already implemented by the classes.,Declares and assigns a new string named s with a value of "Hello Extension Methods".

The following example shows how to call the standard query operator OrderBy method on an array of integers. The expression in parentheses is a lambda expression. Many standard query operators take lambda expressions as parameters, but this isn't a requirement for extension methods. For more information, see Lambda Expressions.

class ExtensionMethods2 {

   static void Main() {
      int[] ints = {
         10,
         45,
         15,
         39,
         21,
         26
      };
      var result = ints.OrderBy(g => g);
      foreach(var i in result) {
         System.Console.Write(i + " ");
      }
   }
}
//Output: 10 15 21 26 39 45
load more v
72%

Note: A class can extend a class and can implement any number of interfaces simultaneously.,Note: An interface can extend any number of interfaces at a time.,The following table explains the difference between the extends and interface:,Access specifier of methods in interfaces

65%

When a subclass extends a class, it allows the subclass to inherit (reuse) and override code defined in the supertype. When a class implements an interface, it allows an object created from the class to be used in any context that expects a value of the interface.,As shown in the figure given below, a class extends another class, an interface extends another interface but a class implements an interface. ,extends is used when you would like to replace details of an existing contract. This way you replace one way to fulfill a contract with a different way. Classes can extend other classes, and interfaces can extend other interfaces.,Difference: implements means you are using the elements of a Java Interface in your class. extends means that you are creating a subclass of the base class you are extending. You can only extend one class in your child class, but you can implement as many interfaces as you would like.

Also java doesn't support multiple inheritance for classes. This is solved by using multiple interfaces.

 public interface ExampleInterface {
    public void doAction();
    public String doThis(int number);
 }

 public class sub implements ExampleInterface {
    public void doAction() {
       //specify what must happen
    }

    public String doThis(int number) {
       //specfiy what must happen
    }
 }

now extending a class

 public class SuperClass {
    public int getNb() {
       //specify what must happen
       return 1;
    }

    public int getNb2() {
       //specify what must happen
       return 2;
    }
 }

 public class SubClass extends SuperClass {
    //you can override the implementation
    @Override
    public int getNb2() {
       return 3;
    }
 }

in this case

  Subclass s = new SubClass();
  s.getNb(); //returns 1
  s.getNb2(); //returns 3

  SuperClass sup = new SuperClass();
  sup.getNb(); //returns 1
  sup.getNb2(); //returns 2
load more v
75%

Unfortunately, this method will only work with classes that expose the Customer interface (that's the Customer class and any class that inherits from Customer). Inheritance makes all of those classes "look alike" to my extension method. ,With this interface in place, I can rewrite my LogInfo method as an extension method that attaches itself to any class that implements ILogInfo: ,As useful as that method is, it exists in only one class. The method would be a lot more useful if it was an extension method so I could use it from other classes. Rewriting the method as an extension method that will still work with the Customer class gives me this code: ,Extension methods provide a great way for extending a class functionality -- but it's interfaces that let you use those methods anywhere you want.

The Problem with Extension Methods
Imagine, for instance, that I have Customer class with a LogInfo method that writes out critical information about the Customer class (in real life, this information would go in a log file, but I'll just write to the console for this example). That method might look something like this:

Public Sub LogInfo()
Console.WriteLine(Me.Name & ":"
   Me.KeyData)
End Sub

As useful as that method is, it exists in only one class. The method would be a lot more useful if it was an extension method so I could use it from other classes. Rewriting the method as an extension method that will still work with the Customer class gives me this code:

Public Module PHVExtensions
<System.Runtime.CompilerServices.Extension()>
   Public Sub LogInfo(ByVal logSubject As Customer)
   Console.WriteLine(logSubject.Name & ": " logSubject.KeyData)
   End Sub
   End Module

With that declaration, this extension method will appear in the IntelliSense list for every .NET class:

Public Module PHVExtensions
  <System.Runtime.CompilerServices.Extension()>
  Public Sub LogInfo(ByVal obj As Object)
    Console.WriteLine(obj.ToString)
  End Sub
End Module


public static class PHVExtensions
{
  public static void LogInfo(this System.Obj obj)
  {
    Console.WriteLine(obj.ToString());
  }
}

In both Visual Basic and C#, the first parameter to an extension method specifies to which kind of object it should attach itself (in these examples, that's System.Object). The object that the method is called from is passed into the extension method through that first parameter. I should be able to write this code, for example, to call the LogInfo method from a Customer object that I've just written:

Dim cust As New Customer
cust.LogInfo()

Leveraging Interfaces
This is where interfaces come in to save the day. Like inheritance, interfaces are a way to make different classes "look alike." I can, for instance, define an interface called ILogInfo that specifies the properties that my LogInfo method requires:

Public Interface ILogInfo
Property Name As String
Property KeyData As String
End Interface

Any class, in addition to whatever objects it inherits from (or whatever other interfaces it already implements), can implement my ILogInfo interface. Here's a Visual Basic class that inherits from an object called CustomerBase and also implements both the IEnumerable and my ILogInfo interfaces (I've also included the properties required by ILogInfo):

Public Class Customer
Inherits CustomerBase
Implements IEnumerable
Implements ILogInfo

Public ReadOnly Property Name() As String Implements ILogInfo.Name
Return "Customer"
End Property

Public ReadOnly Property KeyData() As String Implements ILogInfo.KeyData
Return Me.ID & ", " & Me.Status
End Property

With this interface in place, I can rewrite my LogInfo method as an extension method that attaches itself to any class that implements ILogInfo:

Public Module PHVExtensions
<System.Runtime.CompilerServices.Extension()>
   Public Sub LogInfo(ByVal logSubject As ILogInfo)
   Console.WriteLine(logSubject.Name & ": " logSubject.KeyData)
   End Sub
   End Module
load more v
40%

The engine field in the Auto class accepts any type that implements a TypeScript interface named IEngine and the constructor accepts any object that implements an IAutoOptions interface. Both of these interfaces are shown next:, Let's assume that we have a TypeScript class named Auto that has the following code in it:,The Truck class extends Auto by adding bedLength and fourByFour capabilities. The TypeScript constructor also accepts an object that implements the ITruckOptions interface which in turn extends the IAutoOptions interface shown earlier. Notice that interfaces can also be extended in TypeScript by using the extends keyword:,You have disabled non-critical cookies and are browsing in private mode. For the best possible experience on our website, please accept cookies. For additional details please read our privacy policy.

 

interface IEngine {
   start(callback: (startStatus: bool, engineType: string) => void): void;
   stop(callback: (stopStatus: bool, engineType: string) => void): void;
}

interface IAutoOptions {
   engine: IEngine;
   basePrice: number;
   state: string;
   make: string;
   model: string;
   year: number;
}
load more v
22%

I don't think you need to extend the Employee interface, since you did not indicate that it will need a work() method.,You said I must make a Manager class that is a wrapper for an Employee object Purpose of the wrapper exactly what you described, it wrap some other behavior under own methods. ,When a Manager object is instantiated, it should have all the methods of the underlying Employee plus a few extra. Most of the methods of the underlying Employee object will not be overridden (see work), and thus I think I should be extending Employee. But a class cannot extend an interface. Currently, I am working on declaring each of the Employee methods within the Manager class and having them simply call the corresponding Employee method. But that seems like unnecessary boilerplate and like it will break if the Employee interface ever changes.,If you literally cannot change the Mary class, than you should do a wrapper object like you have, which would act as an Adapter for the Employee class instances.

You don't need inheritance in this case, you need composition:

public interface Manager {
   void manage();
}

public class Mary implements Employee, Manager {
   public void work() {
      //Mary's implementation of work
   }

   public void manage() {
      //manage
   }
}
load more v
60%

A class can implement two interfaces which define a method with the same name, only if the method declaration in both interfaces is identical. , The class implementing the interface must declare all methods in the interface with a compatible signature. , To allow a function or method to accept and operate on a parameter that conforms to an interface, while not caring what else the object may do or how it is implemented. These interfaces are often named like Iterable, Cacheable, Renderable, or so on to describe the significance of the behavior. , All methods declared in an interface must be public; this is the nature of an interface.

Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are implemented. Interfaces share a namespace with classes and traits, so they may not use the same name.

Interfaces are defined in the same way as a class, but with the interface keyword replacing the class keyword and without any of the methods having their contents defined.

interface

Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are implemented. Interfaces share a namespace with classes and traits, so they may not use the same name.

Interfaces are defined in the same way as a class, but with the interface keyword replacing the class keyword and without any of the methods having their contents defined.

class
load more v
48%

Below are enumerated the differences between an interface and a class., To tell the computer that a new class that you are writing will fulfill all the requirements (implement all the functions) of an interface, you must use the keyword implements in the same location where you can use the keyword extends. , No VARIABLES are allowed to be declared by the interface. , They require the programmer to create specific functions that are expected in an implementing class when it implements an Interface.

Here is an example of the Vehicle interface referred to above (only a partial definition).

        package {
           public interface Vehicle {
              // NO data VARIABLES are allowed in an interface
              // only function PROTOTYPES

              /**
               * Comments...
               * Anything that wants to be a "Vehicle" must, implement this function
               */
              function start_engine(): void;

           }
        }

Here is an example of a Car Class which implements the Vehicle definition.

        package {
           public class Car implements Vehicle {

              /**
               * Comments...
               *
               * Here is how we start our car.  This function is mandated by the Vehicle
               * interface.
               */
              function start_engine(): void {
                 // code to start the engine of the car...
              }

           }
        }

With out Interfaces

            // Main Actions
            var car: Car = new Car();
            var truck: Truck = new Truck();

            car.start_engine();
            truck.start_engine();

            car.drive();
            truck.drive();

With Interfaces

            // Main Actions
            var vehicle1: Vehicle = new Car(); // here the only difference is the TYPE of each variable is the same!!!!
            var vehicle2: Vehicle = new Truck();

            vehicle1.start_engine();
            vehicle2.start_engine();

            vehicle1.drive();
            vehicle2.drive();

Using an array and polymorphism

            // Main Actions
            var vehicles: Array = new Array();

            vehicles.push(new Car()); // Assume our program is modeling a game or traffic simulation
            vehicles.push(new Car()); // The Cars and Trucks that we are modeling can be created in
            vehicles.push(new Truck()); // an arbitrary matter.  Normally we would have to create separate
            vehicles.push(new Car()); // arrays for Cars, Trucks, etc.  But because the are all vehicles
            vehicles.push(new Truck()); // we can put them in a single array of Vehicle.
            vehicles.push(new Truck());
            vehicles.push(new Truck());
            vehicles.push(new Car());
            vehicles.push(new Truck());
            vehicles.push(new Car());
            vehicles.push(new Bicycle()); // assume Bicycle is also a Vehicle...
            vehicles.push(new Car());

            // Later on in the program, we want to start all the cars...
            // We can use GENERIC programming (we don't care if they are cars, trucks, bicycle, etc, just that they are vehicles).

            for each(var item: Vehicle in vehicles) {
               item.start_engine();
               item.drive();
            }

Sometimes, you will want to use a function specific to an underlying type. For example, a dump truck implements Vehicle, but additionally has a "raise_bed" function which dumps everything out of the back of the truck. In the following code, the dump truck is thought of by the computer as a Vehicle, and thus the code DOES NOT HAVE ACCESS to the raise_bed function.

        var vehicle: Vehicle = new Dump_Truck();

        vehicle.start_engine(); // ALLOWED: vehicle is a Vehicle and thus has the start_engine function
        vehicle.drive(); // ALLOWED: vehicle is a Vehicle and thus has the start_engine function

        // Compile Time Type error
        vehicle.raise_bed(); // NOT ALLOWED: while in reality (at run time) the vehicle variable
        //              will contain a Dump_Truck and thus this should be a legal
        //              operation, the compiler (at program time) only sees that
        //              vehicle is a Vehicle and the Vehicle class dose not
        //              have a raise_bed function.

To override the computers type checking, you can "take charge" of your program and force the computer to treat the contents of the vehicle variable as a Dump_Truck. Here is the proper code

        var vehicle: Vehicle = new Dump_Truck();

        (vehicle as Dump_Truck).raise_bed(); //  ALLOWED: here the programmer overrides the type checking of the computer.
load more v
23%

Interfaces Extending Classes,Difference between the static and instance sides of classes,We can write the same example again, this time using an interface to describe the requirement of having the label property that is a string:,This is useful when you have a large inheritance hierarchy, but want to specify that your code works with only subclasses that have certain properties. The subclasses don’t have to be related besides inheriting from the base class. For example:

The easiest way to see how interfaces work is to start with a simple example:

tsfunction printLabel(labeledObj: {
   label: string
}) {
   console.log(labeledObj.label);
}
let myObj = {
   size: 10,
   label: "Size 10 Object"
};
printLabel(myObj);
Try
load more v

Other "class-undefined" queries related to "How does a class extension or Interface work?"