Java Series Part 6 – Classes, Objects and Methods

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);
	}

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s