A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
Java is an object-oriented programming language.
Everything in Java is associated with classes and objects, along with its attributes and methods. For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.
A Class is like an object constructor, or a “blueprint” for creating objects.
In Java, an object is created from a class using new Keyword.
To create an object of Main
, specify the class name, followed by the object name, and use the keyword new
:
package com.java.basic;
//Class is like an template
public class Ch6ClassAndMethod {
int var1 = 5;
//method
public static void revolve() {
System.out.println("Revolve");
}
public void revolve2() {
System.out.println("Revolve2");
}
public static void main(String[] args) {
//call the method of class
revolve();
//calling non-static method by creating an instance of class
Ch6ClassAndMethod obj = new Ch6ClassAndMethod();
obj.revolve2();
//accessing variables from objects
System.out.println(obj.var1);
}
}