0% found this document useful (0 votes)
7 views

Lecture-16 Object Class and ToString Method

Uploaded by

Quraisha Azam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Lecture-16 Object Class and ToString Method

Uploaded by

Quraisha Azam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Lecture – 16

Object Class, and toString()


Method
Object Class
• Every class in Java is descended from the java.lang.Object class.
• If no inheritance is specified when a class is defined, the superclass of
the class is Object by default.
• This means that all classes in Java are subclasses of Object, and inherit
certain default behavior and methods from Object, such as the
"equals()", "toString()", and "hashCode()" methods

Public class ClassName{ Public class ClassName extends Object{


Equivalent
… …
} }

4-2
toString() Method
• toString() method is instance method of Object Class
• Signature of toString(): public String toString()
• Invoking toString() on an object returns a string that
describes the object
Loan loan = new Loan();
Loan@15037e5
System.out.println(loan.toString());

• This output is not informative or helpful.


• Usually we override the toString() method
– It returns a descriptive string representation of the object.
4-3
Example
public class Shape { public class Demo{
private String color; public static void main(String[] args){
private boolean filled; Shape s1 = new Shape("red", false);
System.out.println(s1.toString());
public Shape() { System.out.println(s1 );
color = "red"; }
filled = true; }
}

public Shape(String color, boolean filled) {


this.color = color;
this.filled = filled;
} Shape[color=red, filled=false]
... Shape[color=red, filled=false]
@Override
public String toString() {
return "Shape[color=" + color + ", filled=" + filled + "]";
} 4-4

You might also like