PowerShell v5 Classes :: Inheritance & Base Class Methods

Play PowerShell v5 Classes :: Inheritance & Base Class Methods

The Discussion

  • User profile image

    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

    @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.

    Trevor Sullivan
    Microsoft MVP: PowerShell

  • User profile image

    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

    @Minh: You can use the statement


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

  • User profile image
    zameer fouzan

    I have a base class with multiple methods, what I am trying to achieve here is.
    base class with method A and B (to be overridden in derived class).

    class XYZ {
    method B() {} /* overridden in derived */
    method A() { method B(); }

    Class abc : XYZ {
    method B() { /* override*/ }

    is there any possibility in PowerShell that we can refer to method B of ABC from method A of xyz?

Add Your 2 Cents