Main Content

Import Classes

Syntax for Importing Classes

Import classes into a function to simplify access to class members. For example, suppose that there is a package that contains several classes and you will use only one of these classes or a static method in your function. Use the import command to simplify code. Once you have imported the class, you do not need to reference the package name:

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

Import all classes in a package using the syntax pkg.*:

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

Import Static Methods

Use import to import a static method so that you can call this method without using the class name. Call import with the full class name, including any packages, and the static method name.

function myFunc
   import pkg.MyClass.MyStaticMethod 
   MyStaticMethod(arg,...); % call static method
end

Import Package Functions

Use import to import package functions so that you can call these functions without using the package name. Call import with the package and function name.

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

Package Function and Class Method Name Conflict

Avoid importing an entire package using the * wildcard syntax. Doing so imports an unspecified set of names into the local scope. For example, suppose that 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 cannot clear the import list from a function workspace. To clear the base workspace only, use:

clear import

See Also

Related Topics