PowerShell v5 Classes :: Inheritance & Base Class Methods

Sign in to queue

The Discussion

  • User profile image
    JMiz

    Awesome tutorial! I do have a question though, is it possible to use methods from another class without inheritance? For example: can we use the Drive() method from vehicle class in the car class without making car a subclass of the vehicle?

  • User profile image
    pcgeek86

    @JMiz: Nope, that would break the principles of encapsulation! What you're looking for is .NET Interfaces. An interface is essentially a contract, saying that Car class must implement the Drive() method, but the interface itself doesn't actually declare the implementation (method body). The method implementation is the responsibility of the class definition.

    Unfortunately, while you can implement .NET Interfaces in PowerShell classes, you cannot declare an interface in PowerShell syntax.

    Cheers,
    Trevor Sullivan
    Microsoft MVP: PowerShell

  • User profile image
    Minh

    Hey I got a question.
    I try to do is in my class A I have two methods B and C. What i'm trying to do is Inside C method I want to call B. How do I do it? I figured a way but does not feel right, inside method C I created an instance of class A and use that instance to call b method and it work. But is there a better solution for this simple inner class call in powershell

  • User profile image
    bahreex

    @Minh: You can use the statement

    $this.B();

    from within the method C to call method B for the same Object Instance from where this Invocation takes place. HTH. 

Add Your 2 Cents