By Use java program (Netbeans) In this lab, the following topics will be covered
ID: 3776794 • Letter: B
Question
By Use java program (Netbeans)
In this lab, the following topics will be covered Polymorphism Abstract class to string() method Task 1 Java t0 string () method If you want to represent any object as a string, to string() method comes into existence. The to string() method returns the string representation of the object. If you print any object, java compiler internally invokes the to string() method on the object. So overriding the two string() method, returns the desired output, it can be the state of an object etc. depends on your implementation. Advantage of Java to string () method By overriding the two string () method of the Object class, we can return values of the object, so we don't need to write much code. Understanding problem without to string () method Let's see the simple code that prints reference. class Student{int rollno; String name; String city; Student(int rollno, String name, String city){this.rollno=rollno; this.name=name; this.city=city; 10.} public static void main(String args[]){Student s 1 =new Student(101, "Ahmed", "Karachi"); Student s2=nevv Student(102, "Mohammad", "Lahore"); System.out.println(sl);//compiler writes here s1.testring() System.out.println(s2);//compiler writes here $2.testring()}}Explanation / Answer
public class Student {
int rollno;
String name;
String city;
Student(int rollno , String name , String city)
{
this.rollno = rollno;
this.name = name;
this.city = city;
}
/* Returns the string representation Different format.*/
@Override
public String toString() {
return String.format("Different format");
}
public static void main(String []args) {
Student s1 = new Student (101,"Ahmed","Karachi");
Student s2 = new Student (102,"Mohanmad","Lahore");
System.out.println(s1);
System.out.println(s2);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.