Wednesday, January 1, 2020

Methods in java


Methods in java


Method

Methods are the instructions that operate on an object's data to obtain the results. A Class contains both the Data and the Code. The Data is stored in fields and code is applied by methods. In simple words, a method is the implementation of logic in a class. A method basically has two parts

1. Header
2. Body


java methods programminghunk


All the logic is applied inside the method body. The method header has the signature of the method and method modifiers. The method must return the same type which is defined in the method header. The method signature is the composition of the method's name and list of parameters and the type of parameters.

java methods
method



A method can have any of the following modifiers, which direct method to attain certain behaviors.
  1. Access specifiers
  2. abstract
  3. static
  4. final
  5. synchronized 
  6. native
  7. stictfp (strict floating-point evaluation)


Access specifiers


There can be one of four access specifier used with a method
  • public 
  • protected
  • default(no access specifier)
  • private 

abstract


An abstract method does not have its body defined or abstract methods are unimplemented/incomplete methods. Abstract methods are part of Abstract classes and are used to apply Abstraction in Java. 

static


static(read static keyword in Java) methods are class methods and we do not need to create an object of the class to invoke a static method inside that class. We can use the following syntax.

ClassName.staticMethodName()


final


final methods can not be overridden(method overriding in Java) in any subclass.

synchronized


synchronized is related to multi-threading, it means only one thread will access this method at any given point time.

native


The native keyword is used to write code in some native languages like C/C++. The program will compromise its portability and platform independence due to native code.

strictfp


The "strictfp" declared method has all floating-point arithmetic evaluated strictly. A method can not be abstract and final together.  

Video Tutorial