Importing Classes

Syntax for Importing Classes

You can import classes into a function to simplify access to class members. For example, suppose there is a package that contains a number of classes, but you need to use only one of these classes in your function, or perhaps even just a static method from that class. You can use the import command as follows:

function myFunc
   import pkg.cls1 
   obj = cls1(arg,...); % call cls1 constructor
end

Note that you do not need to reference the package name (pkg) once you have imported the class (cls1). You can also import all classes in a package using the syntax pkg.*, where * indicates all classes in the package. For example,

function myFunc
   import pkg.* 
   obj1 = cls1(arg,...); % call pkg.cls1 constructor
   obj2 = cls2(arg,...); % call pkg.cls2 constructor
end

Importing Class Members

You can import the static methods, constant properties, and enumeration names defined in a class so that you do not need to use the package and class name in the importing function. Use the class notation to import class members.

import class package.class.*

For example, myFunc is importing all the members of class pkg.cls1 and the constant property C from class pkg.consts.

function myFunc
   import class pkg.cls1.* 
   import class pkg.consts.C
   obj = cls1(arg,...); % call pkg.cls1 constructor
   m = calcMass;        % call pkg.cls1 static method
   e = m*C^2;           % constant property pkg.const.C
end
  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS