This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English verison of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

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 need to use only one of these classes in your function, or even just a static method from that class. 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.cls1 
   obj = cls1(arg,...);                   % call cls1 constructor
   obj.Prop = cls1.staticMethod(arg,...); % call cls1 static method

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

Import Package Functions

Use import to import package functions:

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

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;

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

More About

Was this topic helpful?