Please use only java commands. Write a class encapsulating the concept of a tele
ID: 3554906 • Letter: P
Question
Please use only java commands.
Write a class encapsulating the concept of a television. Assume a television has a brand and a price. In the television class include a constructor to initialize the brand and price. Include get and set methods as well as a toString method and an equals method that compare two television objects to determine if they are the same brand and have the same price.
Create a client class to test all the methods in the television class. Submit both .java files, both .class files and a screenshot showing the results of your program executing.
for example
private String brand;
private int price;
//Constructor:
public Televioion(String brand, double price){
//we don't really need to use this. , but i just find this way of coding is clearer
this.brand = brand;
this.price = price;
}
//Getter: Gonna get the TV's brand
public String getBrand(){
return brand;
}
//Setter: Set the TV's brand
public void setBrand(String brand){
this.brand = brand;
}
}
not to suffisticated stuff
Explanation / Answer
Program Code:
class Television1
{
private String brand;
private double price;
//Constructor:
public Television1()
{
//Rather than this
//this.brand = brand;
//this.price = price;
//it is more conventional and clear to set the parameters to default values
this.brand="";
this.price=00;
//now we know the values initially are empty or null and change only when the set methods are called
// TODO Auto-generated constructor stub
}
public String getBrand()
{
return brand;
}
public void setBrand(String brand)
{
this.brand = brand;
}
public void setPrice(double price)
{
this.price = price;
}
public double getPrice()
{
return price;
}
public boolean equals(Object other)
{
if (!(other instanceof Television1))
{
return false;
}
Television1 that = (Television1) other;
// Custom equality check here.
return this.brand.equals(that.brand);
}
public String toString()
{
return "" + price;
}
}
public class Television
{
public static void main(String args[])
{
String atv,btv;
double aprice,bprice;
Television1 tv1=new Television1();
tv1.setBrand("Sony");
tv1.setPrice(350.99);
atv=tv1.getBrand();
aprice=tv1.getPrice();
Television1 tv2=new Television1();
tv2.setBrand("Samsung");
tv2.setPrice(299.85);
btv=tv2.getBrand();
bprice=tv2.getPrice();
System.out.println("Price of "+atv+" is "+aprice);
System.out.println("Price of "+btv+" is "+bprice);
//tv1.equals(tv2);
System.out.print("Brand is same: ");
System.out.println(tv1.equals(tv2));
if(aprice==bprice)
{
System.out.println("Price is same for both: "+ tv1);
}
else
{
System.out.println("Price is different for both: "+tv1+" "+tv2);
}
}
}
Sample Outptut:
Price of Sony is 350.99
Price of Samsung is 299.85
Brand is same: false
Price is different for both: 350.99 299.85