OOP - Differences between Methods and Functions
The difference between methods and function is more of semantics (language) than syntax (actual code)
//Code Sample. We will refer to this later. class Car { private String name; private String color; private int topSpeed; public Car(String name, String color, int topSpeed) { this.name = name; this.color = color; this.topSpeed = topSpeed; } public void accelerate() { //vooom! } }
Differences
Method- it is always called using the object of that class in which the method is written. In other words, it is a piece of code that is called by a name that is associated with an object.
- it is implicitly passed on the object on which it was called.
- It is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data).
val car = Car ("polo", "Green", 200) car.accelerate()
Function
- a function is a method which you can call without creating objects. In other words, a function is a piece of code that is called by name and is not associated with an object.
- It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value).
- All data that is passed to a function is explicitly passed.
class HelloWorld{ fun main(args: Array<String>){ greet() } fun greet(){ println("Hello World!") } }
Comments
Post a Comment