When we talk about classes and objects in Java, we need to take some example code to understand the concept of classes and objects. Classes can be represented by the real word entities, and objects are the instance of classes. Let’s take the example of a Pizza shop where we want to write the code for making an order on a pizza shop. We can see that in this scenario shop will be an object real-world entity Pizza will be a real word and Ti and the customer who is going to place the order will be a real word entity.
So in this scenario, we may write the class for pizza in Java example code and we may also write the class for customer example code similarly we are going to write these class examples in Java to learn how we can create the object and how we can define the different attributes of Java.
class Pizza{
//attribtue, staes, variables, data members
//public , private, static, non static attribute, final,
private int price;
private String pizzaName;
private int toppings;
// methods, functions, behaviours, member function
// constructors methods (default constructor without parameetrs)
// user defined constructor
Pizza(){
this.price =0;
this.pizzaName="";
this.toppings=0;
}
Pizza(int p, String pn, int t){
this.price = p;
this.pizzaName = pn;
this.toppings = t;
}
// setter function , methods
public void setPrice(int price ){
this.price= price;
}
public void setPizzaName(String pn){
this.pizzaName = pn;
}
// getter fucntions
public int getPrice(){
return this.price;
}
public String getPizzaName(){
return this.pizzaName;
}
public static void main(String[] args) {
Pizza p1 = new Pizza();
p1.setPrice(50);
p1.setPizzaName("Dominio");
int price = p1.getPrice();
System.out.println("Name = "+p1.getPizzaName());
System.out.println("\nprice of pizza = "+price);
}
}