I need to write a class that encapsulates this program. It should supplement the
ID: 3773941 • Letter: I
Question
I need to write a class that encapsulates this program. It should supplement the constructor, accessors, and mutators. As well as methods like toString and equals.
public class TVSetClient
{
public static void main( String [] args )
{
TVSet tvs1 = new TVSet( "Sony", 1249.99 );
TVSet tvs2 = new TVSet( "RCA", 999.99 );
System.out.println( "The brand of TV set # 1 is " + tvs1.getBrand( ) );
System.out.println( "The price of TV set # 1 is " + tvs1.getPrice( ) );
System.out.println( "TV set # 2 is " + tvs2.toString( ) );
if ( tvs1.equals( tvs2 ) )
System.out.println( "Original TV sets #1 and #2 are identical" );
else
System.out.println( "Original TV sets #1 and #2 are different" );
System.out.println( " Setting TV set #2's brand to Sony and price to 1249.99" );
tvs2.setBrand( "Sony" );
tvs2.setPrice( 1249.99 );
if ( tvs1.equals( tvs2 ) )
System.out.println( "Original TV set #1 and modified TV set #2 are identical" );
else
System.out.println( "Original TV set #1 and modified TV set #2 are different" );
}
}
Explanation / Answer
TVSet.java
public class TVSet {
private String brand;
private double price;
public TVSet(String b, double p){
brand = b;
price = p;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String toString(){
return "brand is "+brand+" price is "+price;
}
public boolean equals(TVSet t){
if(t.brand == this.brand && this.price == t.price){
return true;
}
else{
return false;
}
}
}
TVSetClient.java
public class TVSetClient
{
public static void main( String [] args )
{
TVSet tvs1 = new TVSet( "Sony", 1249.99 );
TVSet tvs2 = new TVSet( "RCA", 999.99 );
System.out.println( "The brand of TV set # 1 is " + tvs1.getBrand( ) );
System.out.println( "The price of TV set # 1 is " + tvs1.getPrice( ) );
System.out.println( "TV set # 2 is " + tvs2.toString( ) );
if ( tvs1.equals( tvs2 ) )
System.out.println( "Original TV sets #1 and #2 are identical" );
else
System.out.println( "Original TV sets #1 and #2 are different" );
System.out.println( " Setting TV set #2's brand to Sony and price to 1249.99" );
tvs2.setBrand( "Sony" );
tvs2.setPrice( 1249.99 );
if ( tvs1.equals( tvs2 ) )
System.out.println( "Original TV set #1 and modified TV set #2 are identical" );
else
System.out.println( "Original TV set #1 and modified TV set #2 are different" );
}
}
Output:
The brand of TV set # 1 is Sony
The price of TV set # 1 is 1249.99
TV set # 2 is brand is RCA price is 999.99
Original TV sets #1 and #2 are different
Setting TV set #2's brand to Sony and price to 1249.99
Original TV set #1 and modified TV set #2 are identical