How to put a subclass object in an array of superclass objects?

In my code, I have two kinds of networks:
classdef Network <handle classdef NetworkMatrix <Network
and one 'holder class': classdef MetaNetwork <handle
which stores Networks (among other things). The holder class has methods to get networks by ID from an internal Map() and a method to get Networks from an array of other Networks.
I use the network matrix class to do some specific matrix alegbra and other operations on these networks, and it updates the map object just fine. However, when I stick a network in the internal network array the code creates a new Network, rather than just creating a reference to the NetworkMatrix object. Therefore, I lose any changes in the networkMatrix that occurs after the Network was initialized.
Question 1: Can I stick a subclass in an array of superclass objects instead of creating a new instance of the superclass object?
Question 2: (Assuming the answer to 1 is no) Can I change the way it pulls out objects without converitng the internal Network Array to a cell array that contains only networks and modifying all of the indexing to cell indexing?

 Akzeptierte Antwort

Andrew Newell
Andrew Newell am 29 Apr. 2011

0 Stimmen

The answer to Question 1 is yes, although how you do it depends on the version of MATLAB. See this discussion on polymorphism.

2 Kommentare

I am using MATLAB R2009a, which seems to leave 'deploying the cell array' or using a converter method as my options. If I create a converter method, does that create a new instance of the superclass object, or does it converte the memory location of the subclass object to a poitner to a similar superclass object? (That is, will everything that points to the old object now point to the converted object?)
It creates a new instance of the superclass object.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Produkte

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by