How to create class with no attributes?

6 Ansichten (letzte 30 Tage)
A.
A. am 7 Mai 2016
Beantwortet: Steven Lord am 9 Mai 2016
  • 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 Kommentare
Geoff Hayes
Geoff Hayes am 8 Mai 2016
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 am 9 Mai 2016
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.

Melden Sie sich an, um zu kommentieren.

Antworten (2)

Elias Gule
Elias Gule am 9 Mai 2016
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 am 9 Mai 2016
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.

Kategorien

Mehr zu Software Development Tools finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by