Classes, objects, methods, packages, constructors, static members, inheritance and polymorphism.
class Pizza extends FoodItem {
Pizza(int price) {
super("Pizza", price);
}
}
Single Inheritance
package vs.oop.inheritence;
class FoodItem {
private String name;
protected int price;
public FoodItem(String name, int price) {
this.name = name;
this.price = price;
}
public int billamount(int qty) {
return(qty * price);
}
}
class Pizza extends FoodItem {
public Pizza(int price) {
super("Pizza", price);
}
}
public class SingleInheritence {
public static void main(String args[]) {
Pizza p = new Pizza(275);
System.out.println("Bill amount: " + p.billamount(4));
}
}
Multi Level Inheritance
package vs.oop.inheritence;
class FoodItem2 {
private String name;
protected int price;
public FoodItem2(String name, int price) {
this.name = name;
this.price = price;
}
public int billamount(int qty) {
return(qty * price);
}
}
class Pizza2 extends FoodItem {
public Pizza2(String n, int price) {
super(n, price);
}
}
class VegPizza extends Pizza2 {
String type;
VegPizza(String t, int price) {
super(t, price);
}
}
public class MultiLevelInheritence {
public static void main(String args[]) {
Pizza2 p = new Pizza2("Pizza", 275);
System.out.println("Bill amount: " + p.billamount(4));
VegPizza v = new VegPizza("Mushroom", 300);
System.out.println("Bill amount: " + v.billamount(2));
}
}
Method overriding - Object class toString() and equals()
class Product {
private int id;
private String name;
Product(int id, String name) {
this.id = id;
this.name = name;
}
@Override public String toString() {
// overriding Object.toString()
return "Product[id=" + id + ", name=" + name + "]";
}
@Override public boolean equals(Object obj) {
// overriding Object.equals()
if(this == obj) return true;
if(!(obj instanceof Product)) return false;
Product other =(Product) obj;
return this.id == other.id&& this.name.equals(other.name);
}
}
class ObjectClassDemo {
public static void main(String[] args) {
Product p1 = new Product(1, "Laptop");
Product p2 = new Product(1, "Laptop");
Product p3 = p1;
System.out.println(p1);
// uses toString()
System.out.println("p1.equals(p2) = " + p1.equals(p2));
// true
System.out.println("p1 == p3 = " +(p1 == p3));
// true (aliases)
}
}
Overloading vs Overriding comparison
class MathCalc {
// OVERLOADING - same name, different parameter lists
int multiply(int a, int b) {
return a * b;
}
int multiply(int a, int b, int c) {
return a *b * c;
}
double multiply(double a, double b) {
return a * b;
}
}
class OverloadVsOverride {
public static void main(String[] args) {
MathCalc mc = new MathCalc();
System.out.println(mc.multiply(3, 4));
// 12
System.out.println(mc.multiply(3,4, 5));
// 60
System.out.println(mc.multiply(2.5, 2.0));
// 5.0
}
}
Login to join the discussion.
No comments yet.