How to create class with no attributes?

조회 수: 12 (최근 30일)
A.
A. 2016년 5월 7일
답변: Steven Lord 2016년 5월 9일
  • Do I need a constructor? If so, how would it look like?
  • Do I use static methods or not?
  • How do I initialise an instance of such a class?
  댓글 수: 2
Geoff Hayes
Geoff Hayes 2016년 5월 8일
A - please describe the purpose this class. If it has no attributes, then does it have a set of methods that perform a certain task or tasks? (So this would be much like a C++ class with static methods only.)
Adam
Adam 2016년 5월 9일
You don't need anything apart from one line to create a class, though obviously it won't do anything:
classdef MyClass
is all you need to define a class.
myObj = MyClass;
will then create an object of the class calling an implicit constructor (you don't need an explicit one).
What else you choose to add to that minimum depends entirely what you want the class to do.

댓글을 달려면 로그인하십시오.

답변 (2개)

Elias Gule
Elias Gule 2016년 5월 9일
In Matlab this class may be created as follows.
classdef MyClass
methods
function myMethod1(this,varargin)
end % myMethod1
end % end of definition of class instance methods
end
this will create a class named MyClass with a default no-parameters constructor. Which can be instantiated as follows
myinstance = MyClass(); % Instantiate MyClass
myinstance.myMethod1(); % Calls the myMethod1 instance method of class MyClass

Steven Lord
Steven Lord 2016년 5월 9일
Do I need a constructor? If so, how would it look like?
It depends on what your object does. If you need to specify some parameters for the object to be instantiated, the constructor is probably the easiest way to do that. [You could instantiate the object with no parameters without creating an explicit constructor then set the properties yourself, but the constructor lets you do that in one place.] If you search the documentation for "constructor method" the first hit should be the page that lists the rules for constructors, gives a few examples, and links to other examples.
Do I use static methods or not?
Again, it depends. Does the method that you want to implement need access to instance-specific data? If so, it shouldn't be Static. For example, if you want to ask for the size of an object, that needs to be called on an instance and so shouldn't be Static. But if it can operate even if there is no instance of the object exists, a Static method may be appropriate.
How do I initialise an instance of such a class?
I think if you describe a little more of what you want your class to do you may receive more specific suggestion for how to design and implement your class.

카테고리

Help CenterFile Exchange에서 Construct and Work with Object Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by