Discussion (8)1
Log in or sign up to continue

Hi Kishan

A method is attached to a specific instance of an Object class.  A Classmethod can be called without having to instantiate the object.

So, we could have a Method on a Person object to update address

do person.UpdateAddress("New address")

Whereas, for a ClassMethod, we could define a Classmethod to give us as object instance to then work on

set person = ##class(User.Person).CreatePerson("FirstName","LastName",Age)

 

Hope that helps?

Not sure if I understood what you meant, but I'll try to answer:

When using class methods you cannot reference your THIS instance. Have you every used Java, C# or whatever programming language that supports object oriented-programming paradigms? If so then class methods are the same as static methods.

Common (non-static) methods have the advantage of providing you the instance context. Which means that all properties are accessible inside this kind of method, even the private ones.

Class Sample.Person Extends %Persistent
{

Property Name As %String;

ClassMethod GetPersonName(instance As Sample.Person)
{
   return instance.Name // This works fine, GetPersonName is receiving an external Sample.Person.
}

// 'My' is used to empathize that this method refers to it's own instance name.
Method GetMyName() As %String 
{
   return ..Name // This also works fine.  Notice that this method doesn't receives the instance, it's because you can only call it from a instance already.
}

ClassMethod GetMyInstanceName() As %String
{
  return ...Name // This won't work. Since there's no context (instance). The compiler will even warn about it.
}
}

A class method is what other languages usually call a static method. One that can be called even without an instance of that class existing.

Let's imagine you have a class Circle. It may have its own radius in a property

set myCircle = ##class(Circle).%New(25)

write myCircle.radius // 25

write myCircle.getArea() // the calculated area based on its own radius

But now you want to quickly calculate the area of a circle with radius 5, but you don't want to instantiate a new Circle object just for that. So you could have a ClassMethod inside the Circle Class that does that for you

write Circle.calcRadius(5)

You could also smash lots of utility functions as ClassMethods into a Utils class.