Documentation

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. You need to use only one of these classes in your function, or perhaps even just a static method from that class. Use the import command as follows:

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

You do not need to reference the package name (pkg) once you have imported the class (cls1). You can import all classes in a package using the syntax pkg.*:

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

Importing Package Functions

Use import to import package functions:

function myFunc
   import pkg.pkfcn 
   pkfcn(arg,...); % call imported package function
end

Package Function and Class Method Name Conflict

Suppose you have the following folder organization:

+pkg/timedata.m % package function
+pkg/@myclass/myclass.m % class definition file
+pkg/@myclass/timedata.m % class method

Import the package and call timedata on an instance of myclass:

import pkg.*
myobj = pkg.myclass;
timedata(myobj)

A call to timedata finds the package function, not the class method because MATLAB® applies the import and finds pkg.timedata first. Do not use a package in cases where you have name conflicts and plan to import the package.

Clearing Import List

You can not clear the import list from a function workspace. To clear the base workspace only, use:

clear import

More About

Was this topic helpful?