What is a class in Java
A class is a prototype or a blueprint from which we can create objects.In real a world, there are many objects which are similar.Think of a class like cars.
How to implement class cars.
/** * * @author Eric * Site:www.techoverload.net * Date:10/26/2017 */ public class Cars { int gearNumber=1; int speed=0; public void changeGear(int value) { gearNumber=value; } public void increaseSpeed(int increment) { speed=speed+increment; } public void decreaseSpeed(int decrement) { speed=speed-decrement; } public void outPut() { System.out.println("Gear " +gearNumber +": Speed " +speed); }
Above class Cars,gearNumber and speed represent object state whereas changeGear, decreaseSpeed,increaseSpeed ,outPut define how the object will interact with outside world.
If you have realized,the above class does not have the main method.This is because above class is a blueprint for creating new objects.Example code that create two cars objects.
/** * * @author Eric * Site:www.techoverload.net * Date:10/26/2017 */ public class CarsDemo { public static void main(String args[]) { Cars car1=new Cars();//car object one Cars car2=new Cars();//car object two car1.changeGear(3); car1.decreaseSpeed(30); car1.outPut(); car2.changeGear(2); car2.decreaseSpeed(40); car2.outPut(); } }