Programming
OOP – Differences between Methods and Functions
Basically there is not much difference between them (method and functions).
//Car Class 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).
// Example of a Method //Java Car car = new Car ("polo", "Green", 200); car.accelerate(); //Kotlin 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.
Example of a Function // Java Code public class HelloWorld{ protected void main(ArrayList<String> args){ greet(); } private void greet(){ System.out.print("Hello World!"); } } // Kotlin Code class HelloWorld{ fun main(args: Array<String>){ greet() } fun greet(){ println("Hello World!") } }
[box type=”shadow” align=”” class=”” width=””]
Further Reading
- Kotlin Method Examples
[/box]