Tech Master Tutorials
Email Facebook Google LinkedIn Pinterest Twitter
Home Java Java 8 Java Interview Questions Java8 Interview Questions Object Oriented Programming in Java JVM Java Programming

Classes and Objects

Class

Class is the template for objects/entities.
Or we can say that class defines the states and behaviours for a type of object.

e.g In the following example, Student is the class that defines the template for a student.
Using this template, we can create objects.
package oops.classes;

public class Student {
	private String name;
	private int rollNumber;
	private String address;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getRollNumber() {
		return rollNumber;
	}

	public void setRollNumber(int rollNumber) {
		this.rollNumber = rollNumber;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}
}



Types of classes in java :
  • Concerete class :
    • Classes that can be instantiated and inherited
    • Concrete classes have all concrete methods and constructors. Concrete methods are those methods that can be declared along with the definitions and can be overridden.
  • Abstract class :
    • Abstract classes have atleast one abstract method
    • Abstract classes can have constructors but can not be instantiated
    • Abstract classes need to be inherite to be used>
  • Final class :
    • Final classes are concrete classes that can not be inherited


Types of methods in a class :
  • Concerete method :
    • Concrete methods are those methods that can be declared along with the definitions
    • Concrete methods can be overridden
  • Abstract method :
    • Abstract methodes can only be declared along with the parameters
    • Abstract methodes can not have definitions
  • Final method :
    • Final methods are concrete methodes that can not be overrodden

Object

Object is a collection of the states and behaviours. An object in java corresponds to the real life entity.
In the class section, we defined this below student class.
Using the same class, creating student object in the below example:
package oops.classes;

public class ObjectTest {
	
	public static void main(String[] args) {
		//creating student object with new keyword 
		Student studentObj = new Student();
		
		//setting student states
		studentObj.setName("Name");
		studentObj.setAddress("US");
		studentObj.setRollNumber(1);
		
		
		System.out.println("Student name : " +studentObj.getName() + 
				", Address = "+ studentObj.getAddress() + 
				" rollNumber = "+studentObj.getRollNumber());
		
	}

}