PhysicsTeacher.in

High School Physics + more

Java Program – overriding a method inherited from Object class

Here is a Java program that helps you to understand how to override a method. In this program, a class overrides the “equals” method inherited from the Object class in Java.

Java program to Override a method inherited from Object class in Java

class Room
{int l,b,h;
Room(int l,int b,int h)
{
this.l=l;
this.b=b;
this.h=h;
}

void show()
{System.out.println(“DATA:”+l+” “+b+” “+h);
}

/* overriding equals method inherited from Object class,
Note: class instance is used as method parameter */
boolean equals(Room r)
{
if(r.l==l && r.b==b && r.h==h) return true;
else return false;
}
}

class EqualityTest
{
public static void main(String args[])
{
Room r1=new Room(10,12,14);
Room r2=new Room(10,12,14);
Room r11=r1;

System.out.println(“r1.equals(r2)returns::::”+r1.equals(r2));//!!!!

System.out.println(“r1==r2 check returns::::”+(r1==r2));

System.out.println(“r1.equals(r11))returns::::”+ (r1.equals(r11)));

System.out.println(“r1==r11 check returns::::”+(r1==r11));

}

}

See also  Chemical equation and balancing chemical equations
Scroll to top
error: physicsTeacher.in