Java Classes and Methods

<<Previous: A Simple Hello World Program

Next : Interfaces >>




A class is a type definition of a real world or an application entity or object.

For example, if you consider Car as a class. Each specific car becomes an object. In other words, to represent different specific cars, you need to create a class named Car.

A class always has properties and behaviours.

class Car{
	//members
}

For example, Car class can have the following properties and represented in Java as member variables of class.

  • engine
  • tyres
  • body
  • wheels
  • and so on

Car class can have behaviors such as:

  • drive Car
  • apply Brakes
  • turn Steering Wheel
  • start Engine
  • on AC
  • on Wipers
  • and so on.

These properties and behaviours would be written as member variables and methods in a class as shown below

public class Car{

	String engineName;
	int numberOfTyres;
	String tyreType;
	String bodyMetal;
	int wheelWeight;

	void driveCar(){
	}

	int applyBrakes() {
		//onsuccess
		return 1;
	}

	void turnSteeringWheel() {
	}

	String startEngine() {
		//onsuccess
		return "STARTED";
	}

	void onAC() {
	}

	void onWipers() {
	}
}

Similarly, you can create class to represent anything:

  • class World
  • class Sea
  • class Employee
  • class Student
  • class Organization
  • class Company
  • class Vehicle
  • class TransportationMode
  • class Shop
  • class Pencil
  • class Human
  • class Animal
  • class Table
  • class Road
  • class Application
  • class Box

and so on.

Let us look at a different example for creating a class: Employee

Example

public class Employee{
	int id;
	String name;
	float salary;

	public Employee(int id, String name, float salary){
		this.id= id;
		this.name= name;
		this.salary= salary;
	}
	public void printEmployeeDetails(){
		System.out.println("Salary of Employee "+ name
						+ " with ID " + id + " " + salary);
	}

	public static void main(String args[]){
		Employee emp = new Employee(2,"Sachin",25000.00f);
		emp.printEmployeeDetails();
	}
}

You can create classes for anything generic in nature. Once you create one class, you can create one or several objects with it.

ClassObjectDescription
StudentEach studentFor example, if you create a class named Student, you can create several Student objects
Car Each carFor example, if you create a class named Car, you can create several car objects or instances with different vehicle numbers
EmployeeEach employeeFor example, if you create a class named Employee, you can create employee instances or objects

Usual High level Ways to create Objects

When you create a software application, you create one or more classes you need.

For each class, You can

  • create one or more objects when the application starts up.
  • create one or more objects for the class during progam execution.
  • let user actions or system events create the objects from a class dynamically.

You can create objects in the way, you need your application to work.

Ways To Create An Application

Most applications include the following actions and more..

  • Methods in one class will create objects of one ore classes and invoke its methods.
  • Some of the invoked methods may create other objects and may or may not invoke its menthods.
  • Thus, creating a number of objects and methods calls and does a lot of functionality.
  • This eventually builds up an application.
  • Thus an application is created from a number of classes.
  • The entire application starts from a single starting point.

Java Class Components

Everything in Java except for the package, import statements, enums and interfaces, everything else is defined within a Class.

In Java, A class can have:

  • Fields - fields are represented as variables in Java. Fields can store values. In regular usage, Fields are also sometimes referred to as properties or attributes
  • Methods - methods are also referred to as behaviours. Methods in Java are similar to functions in C and C++. Methods have lines of code which perform some actions.
  • Static Blocks - static blocks contain actions which need to be performed as soon as a class is loaded
  • Nested Classes - classes defined within classes are called nested classes. We would learn nested classes later in the tutorial

Java Objects

An object is an instance of a Java class. There are several ways to create a Java object.

We will look at simple ways to create an object.

  • creating the 'new' operator or
  • using the Object.clone() method

public class MyApplication{
	public static void main(String a[]) {
		Employee emp = new Employee(2,"Harry",25000.00f);
		emp.printEmployeeDetails();
		Employee emp2;
		try {
			emp2 = emp.clone();
		} catch (CloneNotSupportedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

More ways to create objects

If you are interested to know more, you can go through the below list. However, you might want to go through this list when you have gained some level of expertise in Java.

  • using reflection with the Constructor.newInstance()
  • using reflection with the Class.newInstance()
  • objects created for anonymous classes
  • objects created for Lambda expressions
  • objects created when deserializing
  • objects created because of autoboxing
  • arrays are created as objects by default
  • varargs using Object... in method calls are created as arrays and hence as objects by default
  • Strings created with " " (double quotes) are actually objects

Java Methods

Any operation or behaviour is defined by a method in Java. Methods are similar to Functions in other programming languages. A method is defined within a class.

A method can take zero, one or more parameters as input and return one parameter as output

Examples of methods:

Method below takes no parameter as input and returns void. It is a public method and can be invoked on an instance within the same or different package.

public void invoke(){
		System.out.println("I am invoked");
	}

Method below takes no parameter as input and returns long value. It is a private method and can be invoked only within class and not on an instance.


	private long getID(){
		long id = System.currentTimeMillis();
		return id;
	}

Method below takes two int parameters as input and returns one int value. It is a default method (meaning, with no private or public qualifier mentioned) and can be invoked on an instance which is within the same but not different package.


	 int findSum(int x, int y){
	 	int z = x + y;
		return z;
	}

<<Previous: A Simple Hello World Program

Next : Interfaces >>







Java Classes and Methods

<<Previous: A Simple Hello World Program

Next : Interfaces >>




A class is a type definition of a real world or an application entity or object.

For example, if you consider Car as a class. Each specific car becomes an object. In other words, to represent different specific cars, you need to create a class named Car.

A class always has properties and behaviours.

class Car{
	//members
}

For example, Car class can have the following properties and represented in Java as member variables of class.

  • engine
  • tyres
  • body
  • wheels
  • and so on

Car class can have behaviors such as:

  • drive Car
  • apply Brakes
  • turn Steering Wheel
  • start Engine
  • on AC
  • on Wipers
  • and so on.

These properties and behaviours would be written as member variables and methods in a class as shown below

public class Car{

	String engineName;
	int numberOfTyres;
	String tyreType;
	String bodyMetal;
	int wheelWeight;

	void driveCar(){
	}

	int applyBrakes() {
		//onsuccess
		return 1;
	}

	void turnSteeringWheel() {
	}

	String startEngine() {
		//onsuccess
		return "STARTED";
	}

	void onAC() {
	}

	void onWipers() {
	}
}

Similarly, you can create class to represent anything:

  • class World
  • class Sea
  • class Employee
  • class Student
  • class Organization
  • class Company
  • class Vehicle
  • class TransportationMode
  • class Shop
  • class Pencil
  • class Human
  • class Animal
  • class Table
  • class Road
  • class Application
  • class Box

and so on.

Let us look at a different example for creating a class: Employee

Example

public class Employee{
	int id;
	String name;
	float salary;

	public Employee(int id, String name, float salary){
		this.id= id;
		this.name= name;
		this.salary= salary;
	}
	public void printEmployeeDetails(){
		System.out.println("Salary of Employee "+ name
						+ " with ID " + id + " " + salary);
	}

	public static void main(String args[]){
		Employee emp = new Employee(2,"Sachin",25000.00f);
		emp.printEmployeeDetails();
	}
}

You can create classes for anything generic in nature. Once you create one class, you can create one or several objects with it.

ClassObjectDescription
StudentEach studentFor example, if you create a class named Student, you can create several Student objects
Car Each carFor example, if you create a class named Car, you can create several car objects or instances with different vehicle numbers
EmployeeEach employeeFor example, if you create a class named Employee, you can create employee instances or objects

Usual High level Ways to create Objects

When you create a software application, you create one or more classes you need.

For each class, You can

  • create one or more objects when the application starts up.
  • create one or more objects for the class during progam execution.
  • let user actions or system events create the objects from a class dynamically.

You can create objects in the way, you need your application to work.

Ways To Create An Application

Most applications include the following actions and more..

  • Methods in one class will create objects of one ore classes and invoke its methods.
  • Some of the invoked methods may create other objects and may or may not invoke its menthods.
  • Thus, creating a number of objects and methods calls and does a lot of functionality.
  • This eventually builds up an application.
  • Thus an application is created from a number of classes.
  • The entire application starts from a single starting point.

Java Class Components

Everything in Java except for the package, import statements, enums and interfaces, everything else is defined within a Class.

In Java, A class can have:

  • Fields - fields are represented as variables in Java. Fields can store values. In regular usage, Fields are also sometimes referred to as properties or attributes
  • Methods - methods are also referred to as behaviours. Methods in Java are similar to functions in C and C++. Methods have lines of code which perform some actions.
  • Static Blocks - static blocks contain actions which need to be performed as soon as a class is loaded
  • Nested Classes - classes defined within classes are called nested classes. We would learn nested classes later in the tutorial

Java Objects

An object is an instance of a Java class. There are several ways to create a Java object.

We will look at simple ways to create an object.

  • creating the 'new' operator or
  • using the Object.clone() method

public class MyApplication{
	public static void main(String a[]) {
		Employee emp = new Employee(2,"Harry",25000.00f);
		emp.printEmployeeDetails();
		Employee emp2;
		try {
			emp2 = emp.clone();
		} catch (CloneNotSupportedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

More ways to create objects

If you are interested to know more, you can go through the below list. However, you might want to go through this list when you have gained some level of expertise in Java.

  • using reflection with the Constructor.newInstance()
  • using reflection with the Class.newInstance()
  • objects created for anonymous classes
  • objects created for Lambda expressions
  • objects created when deserializing
  • objects created because of autoboxing
  • arrays are created as objects by default
  • varargs using Object... in method calls are created as arrays and hence as objects by default
  • Strings created with " " (double quotes) are actually objects

Java Methods

Any operation or behaviour is defined by a method in Java. Methods are similar to Functions in other programming languages. A method is defined within a class.

A method can take zero, one or more parameters as input and return one parameter as output

Examples of methods:

Method below takes no parameter as input and returns void. It is a public method and can be invoked on an instance within the same or different package.

public void invoke(){
		System.out.println("I am invoked");
	}

Method below takes no parameter as input and returns long value. It is a private method and can be invoked only within class and not on an instance.


	private long getID(){
		long id = System.currentTimeMillis();
		return id;
	}

Method below takes two int parameters as input and returns one int value. It is a default method (meaning, with no private or public qualifier mentioned) and can be invoked on an instance which is within the same but not different package.


	 int findSum(int x, int y){
	 	int z = x + y;
		return z;
	}

<<Previous: A Simple Hello World Program

Next : Interfaces >>







Learn about Stack Data Structure

Learn about Heap Data Structure

Learn about Operating System

Learn AVL Tree

Learn Djikstra's Algorithm