Concepts Practiced
- Class & Objects
- Instance Variables
- Static Variable
- Constructors
- Constructor Overloading
-
thisKeyword - Methods
- Method Parameters
- Method Overloading
- Compile-Time Polymorphism
- Return Type &
returnKeyword - Static & Non-Static Methods
- Calling Methods using Objects
- Separate Methods for GPay, Cash & Card
Code:
public class Supermarket{
static String supermarketName = "Grace";
String productName;
int price;
int quantity;
//creating multiple constructors with same class name and different parameter list
public Supermarket(String productName){
this.productName = productName;
// this.quantity = quantity;
}
public Supermarket(String productName, int price, int quantity){
this.productName = productName;
this.price = price;
this.quantity = quantity;
}
public Supermarket(String productName, int price)
{
this.productName = productName;
this.price = price;
}
public static void main(String[] args){
// System.out.println("Hello World");
Supermarket product1 = new Supermarket("milk");
Supermarket product2 = new Supermarket("curd", 20);
Supermarket product3 = new Supermarket("Biscuit", 10, 3);
product1.buy();
product2.buy(30);
product3.buy(20,"Hi");
//calling non-static return type function
int finalPrice = product1.buy(50,5);
System.out.println("finalPrice: "+finalPrice);
//calling gpay, cash, card methods
product3.gpay(200);
product3.cash(100);
product3.card(500);
}
//creating multiple methods with same method name with different parameters list in the same class
public void buy(){
// System.out.println("Buy Method");
}
public void buy(int account){
// System.out.println("Buy Method - account");
// System.out.println(this.price);
}
public void buy(int i, String payName){
// System.out.println("Buy Method");
}
//creating method with return type
public int buy(int price, int discount){
int total = price - discount;
return total;
}
//creating method for gpay
public void gpay(int amount){
System.out.println("Payment via Gpay");
System.out.println("Amount: "+ amount);
}
//creating method for cash
public void cash(int amount){
System.out.println("Payment via Cash");
System.out.println("Amount: "+ amount);
}
//creating method for card
public void card(int amount){
System.out.println("Payment via Card");
System.out.println("Amount: "+ amount);
}
}
Output:
finalPrice: 45
Payment via Gpay
Amount: 200
Payment via Cash
Amount: 100
Payment via Card
Amount: 500
Top comments (0)