Consider a class Computer having . Two fields ( i.e. companyName , price ) and A single function named show ( ) A class named Desktop inherits Computer class and adds fields representing color , monitor size , and processor type and Override function named show ( ) to display values of its all attributes . A class named Laptop inherits Computer class and adds fields representing color , size , weight , and processor type and Override function named show ( ) to display values of its all attributes . Write a main ( ) function that instantiates objects of derived classes to access respective show ( ) function using dynamic binding .
public class Computer {
private String companyName;
private double price;
public Computer(String companyName, double price) {
this.companyName = companyName;
this.price = price;
}
public void show() {
System.out.println("Company name: " + companyName + ", price: " + price);
}
}
public class Desktop extends Computer {
private String color;
private double monitorSize;
private String processorType;
public Desktop(String companyName, double price, String color, double monitorSize, String processorType) {
super(companyName, price);
this.color = color;
this.monitorSize = monitorSize;
this.processorType = processorType;
}
@Override
public void show() {
super.show();
System.out.println("Color: " + color + ", monitor size: " + monitorSize + ", processor type: " + processorType);
}
}
public class Laptop extends Computer {
private String color;
private double size;
private double weight;
private String processorType;
public Laptop(String companyName, double price, String color, double size, double weight, String processorType) {
super(companyName, price);
this.color = color;
this.size = size;
this.weight = weight;
this.processorType = processorType;
}
@Override
public void show() {
super.show();
System.out.println("Color: " + color + ", size: " + size + ", weight: " + weight + ", processor type: " + processorType);
}
}
public class Main {
public static void main(String[] args) {
Computer desktop = new Desktop("HP",125.6,"Red",24,"ARM");
Computer laptop = new Laptop("Dell",200.4,"Red",24,10,"RISC");
desktop.show();
System.out.println();
laptop.show();
}
}
Comments
Leave a comment