Inheritance Polymorphism In Matlab

2019-06-28 03:25发布

问题:

I was trying to read the matlab docs for a while, and either this doesn't exist or they named it something that did not occur to me.

In mainstream languages such as Java for example, I can implement the Strategy pattern with simple polymorphism like so:

class A{
    void foo(){
        System.out.println("A");
    }
}

class B : A{
    void foo(){
        System.out.println("B");
    }
}

A ab = new B();
ab.foo();//prints B, although static type is A.

the same concept is also available in interpreter languages such as python.

Is there something like this in Matlab (I'm using 2016a).

What is it called? what is the syntax?

回答1:

classdef A < handle
    %UNTITLED Summary of this class goes here
    %   Detailed explanation goes here

    methods
         function obj =  A ()            
         end         
        function printSomething (obj)
            disp ('Object of class A') ;
        end        
    end    
end


classdef B < A
    %UNTITLED2 Summary of this class goes here
    %   Detailed explanation goes here

    methods
        function obj =  B ()
        end
        function printSomething (obj)
            disp ('Object of class B');
        end
    end    
end

creation of instance of class A:

a = A () ;
a.printSomething ();

By executing above line of code, you will see:

Object of class A

creation of instance of class B:

b = B () ;
b.printSomething()

By executing above line of code, you will see:

Object of class B

Type checking:

isa (b,'A')

1

isa (b,'B')

1