I have a couple to class in which I'm getting and setting a few things and then finally calling it in my main method. But when I call my class in the main method it just gives me the object instead of name,address and age. I know this structure is very complicated but I want to keep this structure because later on I will be adding a lot of things to this. It would be AMAZING if someone could tell me how to do this. I would really appreciate this. Below is my code for all my classes
This is my first class
public class methodOne
{
public String getName()
{
String name = "UserOne";
return name;
}
public int getAge()
{
int age = 17;
return age;
}
public String getAddress()
{
String address = "United States";
return address;
}
}
This is my second class
public class methodTwo
{
String name;
String address;
int age;
public methodTwo(methodOne objectOne)
{
name=objectOne.getName();
address=objectOne.getAddress();
age=objectOne.getAge();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
This is my third class
public class methodThree {
private methodTwo methodTwoInMethodThree;
private methodOne methodOneInMethodThree;
public methodThree()
{
this.methodOneInMethodThree = new methodOne();
this.methodTwoInMethodThree = new methodTwo(methodOneInMethodThree);
}
public methodTwo getMethodTwoInMethodThree() {
return methodTwoInMethodThree;
}
public void setMethodTwoInMethodThree(methodTwo methodTwoInMethodThree) {
this.methodTwoInMethodThree = methodTwoInMethodThree;
}
}
This is my fourth class which is the method maker
public class methodMaker {
public methodThree brandNewFunction(methodTwo object)
{
methodThree thirdMethod = new methodThree();
thirdMethod.setMethodTwoInMethodThree(object);
return thirdMethod;
}
}
This is my main class which calls methodMaker. What I want to achieve is that when I print the value it should print the name,address and age but instead it just prints trial.methodThree#4de5ed7b
public class mainClass {
public static void main(String args[])
{
methodMaker makerOfMethods = new methodMaker();
methodOne one = new methodOne();
methodTwo object = new methodTwo(one);
System.out.println(makerOfMethods.brandNewFunction(object).toString());
}
}
What you need to do is to override the default implementation of the .toString() method in the objects you want to print out:
#Override
public String toString()
{
return "Name: " + this.name;
}
EDIT:
I do not know exactly where you are printing, and you naming convention doesn't really help out, but from what I am understanding, you would need to implement it in all of you classes since they all seem to be related to each other.
So, in your methodOne class (can also be applied to methodTwo):
#Override
public String toString()
{
return "Name: " + this.name + " Age: " + this.age + " Address: + " this.address;
}
In your methodThree class:
private methodTwo methodTwoInMethodThree;
private methodOne methodOneInMethodThree;
#Override
public String toString()
{
StringBulder sb = new StringBuilder();
if(this.methodTwoInMethodThree != null)
{
sb.append("Method 2:").append(methodTwoInMethodThree.toString());
}
if(methodOneInMethodThree != null)
{
sb.append("Method 1:").append(methodOneInMethodThree.toString());
}
return sb.toString();
}
When you call
MyClass myObject = new MyClass();
System.out.println(myObject);
Implicitly , java calls instead
System.out.println(myObject.toString());
So, if in MyClass, you override toString(), then whatever your toString method returns is what's gonna be printed.
Side note: are you confusing classes and methods? Methods are functions in your classes, classes are wrappers around a bunch of attributes and methods. Your naming is confusing.
try this code:
public class methodTwo
{
String name;
String address;
int age;
public methodTwo(methodOne objectOne)
{
name=objectOne.getName();
address=objectOne.getAddress();
age=objectOne.getAge();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return name+" "+address+" "+age;
}
}
Are you printing the object using println()?
From the docs, println():
calls at first String.valueOf(x) to get the printed object's string value
This string value is obtained from the object's toString() method, which:
returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object
So if you want to print anything other than this you have to override the toString() method in your object and return a string containing whatever you want.
Just google "override tostring java" and you will see a ton of examples.
Related
This is the class with the toString method
class Person {
final String name;
final String address;
final String phoneNr;
Person(String name, String address, String phoneNr) {
this.name = name;
this.address = address;
this.phoneNr = phoneNr;
}
#Override
public String toString() {
return String.format("%-10s, %-20s, %-10s", name, address, phoneNr);
}
}
Now I need to write this method in a PhoneBookList class that I created earlier. How would i do this?
Just override toString() this in Person class and in Phonebooklist when printing any person object will use toString() values
public class Person {
#Override
public String toString() {
return String.format("%-10s, %-20s, %-10s", name, address, phoneNr);
}
}
public class Phonebooklist {
public static void main(String[] args) {
Person person = new Person("name", "address", "000-000-000"); // if you are using constuctor overloading
System.out.println(person);
}
}
, And if you loop over all nodes in Phonebooklist and use Person's toString format you can do this like this:
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
Node current = head;
while (current != null) {
builder.append(current.person); // this will append person object and use it's toString with this format "%-10s, %-20s, %-10s", name, address, phoneNr
if (current.next != null) builder.append("\n");
current = current.next;
}
return builder.toString();
}
I have super class called pojo. I have a subclass called ExtendPojo.
pojo.java
package com.java.pojo;
public class pojo {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public long getNumber() {
return number;
}
public void setNumber(long number) {
this.number = number;
}
public String toString() {
return "pojo [name=" + name + ", age=" + age + ", number=" + number + "]";
}
private String name;
private int age;
private long number;
}
ExtendPojo.java
package com.java.pojo;
public class ExtendPojo extends pojo{
public static void main(String[] args) {
pojo obj = new pojo();
obj.setName("santhosh");
ExtendPojo exObj = new ExtendPojo();
exObj.setName("mahesh");//It is not overriding
System.out.println(obj.getName());//it prints santhosh.
}
public void setName(String name){
super.setName(name);
}
}
You are creating two independent objects.
First you create an object and name it santhosh. This object is referenced by the obj variable.
pojo obj = new pojo();
obj.setName("santhosh");
Then you create a second object, which is referenced by the exObj variable.
ExtendPojo exObj = new ExtendPojo();
It doesn't have a name yet, since it's a new object and you haven't assigned the name. You then give it a name.
exObj.setName("mahesh");//It is not overriding
Now you print the name of the first object, which hasn't changed.
System.out.println(obj.getName());//it prints santhosh.
The code is doing exactly what you asked it to do.
If you intended the two variables to reference the same object, you'd do this:
ExtendPojo exObj = new ExtendPojo();
pojo obj = exObj ;//Same object, new variable, different type
obj.setName("santhosh");
exObj.setName("mahesh");//It is working now
System.out.println(obj.getName());//it prints mahesh.
I have gone through the Inheritance and method overriding concepts and clarified my doubts :)
public class ExtendPojo extends Pojo{
public static void main(String[] args) {
Pojo obj = new Pojo();
obj.setName("santhosh");
Pojo obj1 = new ExtendPojo();
obj1.setName("mahesh");//It is overriding now
System.out.println(obj1.getName());//it prints mahesh.
}
}
I am trying to print the individual objects in the players class(performance, injured and name) and on the main class I am trying to print the entire player object however when I try executing the toString(); method on both classes, I just receive player#2eb3998c or Main#37e6e526. Where am I going wrong?
Thanks for any help.
Player class:
package com.laurens;
/**
* Created by laurensvanoorschot on 20-01-16.
*/
public class player {
private String name;
private int performance;
private boolean injured;
public player(int performance, boolean injured, String name) {
this.injured = injured;
this.name = name;
this.performance = performance;
}
public boolean isInjured() {
return injured;
}
public void setInjured(boolean injured) {
this.injured = injured;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPerformance() {
return performance;
}
public void setPerformance(int performance) {
this.performance = performance;
}
#Override
public String toString() {
return "com.laurens.player{" +
"injured=" + injured +
", name='" + name + '\'' +
", performance=" + performance +
'}';
}
}
main Class:
package com.laurens;
public class Main {
private player player;
public static void main(String[] args) {
player player = new player (4, true, "laurens");
player.toString();
}
public com.laurens.player getPlayer() {
return player;
}
#Override
public String toString() {
return super.toString();
}
public void setPlayer (int performance, String name) {
if (performance < 4) {
boolean injured = true;
}
}
}
Most likely, you simply forgot to recompile your classes; your Player code is fine (and you have errors in your Main class that you aren't aware of, which suggests no recompile). That said, there's nothing in your posted code that actually prints anything. System.out.println (actually, any PrintWriter print methods) will automatically call toString() on an object, so there's no need to do that yourself, just
System.out.println(player);
Use
System.out.println(player.toString());
toString() returns a string/textual representation of the object. How to use the toString method in Java?
Explicitly calling print, displays your properties fine:
System.out.println(player.toString());
as well as:
System.out.println(player);
I have a small problem with printing out strings that are stored in an object. The object is stored in an ArrayList.
I have three clases that I use im my program:
Friend Class:
package one;
public class Friend implements InterfaceFriend {
private String name;
private String email;
private String phone;
public Friend(String name, String phone, String email) {
// TODO Auto-generated constructor stub
}
#Override
public String getPhone() {
return phone;
}
#Override
public String getEmail() {
return email;
}
#Override
public String getName() {
return name;
}
#Override
public void setPhone(String phone1) {
phone1 = phone;
}
#Override
public void setEmail(String email1) {
email1 = email;
}
#Override
public void setName(String name1) {
name1 = name;
}
}
FriendInterface:
package one;
public interface InterfaceFriend {
String getPhone(); // Returns phone number.
String getEmail(); // Returns email.
String getName(); // Returns name.
void setPhone(String phone); // Sets phone.
void setEmail(String email); // Sets email.
void setName(String name); // Sets name.
}
and Test Class:
package one;
import java.util.ArrayList;
import java.util.List;
public class FriendTest {
static List<Friend> friends;
static Friend friend;
public static void main(String args[]) {
friends = new ArrayList<Friend>();
friend = new Friend("Jane Doe", "085-5555555", "jane.doe#gmail.com");
friends.add(friend);
friend = new Friend("John Doe", "085-1111111", "john.doe#gmail.com");
friends.add(friend);
friend = new Friend("Paul Weller", "085-3333333", "paul.weller#gmail.com");
friends.add(friend);
System.out.println("Friends added to list:");
System.out.println(friends.toString());
}
}
The problem is that when I am running the System.out.println(friends.toString());from the Test Class i am getting this:
Friends added to list:
[one.Friend#38f0b51d, one.Friend#4302a01f, one.Friend#615e7597]
Instead the Strings with the values that I want. Any help appreciated.
You'll need to override the toString() method in the Friend class as commented already, but you also need to complete the constructor that you're using.
public Friend(String name, String phone, String email) {
this.name = name;
this.phone = phone;
this.email = email;
}
Moreover, the code in your setters are backwards.
In you friend class you need to override toString()
public class Friend implements InterfaceFriend {
...
...
public String toString(){
return name + " " + email + " " + phone; // or whatever format you want printed
}
}
you simply override toString method. place this inside of Friend class. problem solved..
public String toString(){
// return your Strings..
}
Override to toString() in your class, to what output suits you. The reason you're getting that output is because the default toString() provided in objects is a hash code.
public String toString(){
return name; //assuming you only want to display the name else edit it
}
When I run the code below, why does it throw this error?
Exception in thread "main" java.lang.CloneNotSupportedException: Student
at java.lang.Object.clone(Native Method)
at Student.clone(Student.java:44)
at StudentApp.main(StudentApp.java:10)
Here's my main class:
public static void main(String[] args) throws CloneNotSupportedException {
Address address = new Address("湖南省长沙市林科大","1234567",20);
Student stu = new Student("诸葛亮量",20);
stu.setAddress(address);
Student stu2 = (Student)stu.clone();
stu2.setAddress(new Address("湖南省常德市区","484848348",22));
stu2.setName("张飞飞");
stu2.setAge(23);
stu.sayHi();
stu2.sayHi();
}
This is Student class:
public class Student{
private String name;
private int age;
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Student() {
super();
}
#Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public void sayHi() {
System.out.println("大家好,我是" + this.getName() + "同学,我今年" + this.getAge()
+ "岁了……我的HashCode是:" + this.hashCode()+"。我家庭住址是"+address.getAddress()+",家庭住址的HashCode为:"+address.hashCode());
}
}
This is Address Class:
public class Address {
private String address;
private String tel;
private int roadNum;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public int getRoadNum() {
return roadNum;
}
public void setRoadNum(int roadNum) {
this.roadNum = roadNum;
}
public Address() {
super();
}
public Address(String address, String tel, int roadNum) {
super();
this.address = address;
this.tel = tel;
this.roadNum = roadNum;
}
}
From the javadoc
Invoking Object's clone method on an instance that does not implement
the Cloneable interface results in the exception
CloneNotSupportedException being thrown.
Have you tried to make your Student class implement the Cloneable interface?
Instead of attempting to use clone(), write a copy constructor that takes an instance of a Student and copies it's fields individually. Then you don't need to worry about the semantics of clone. In your example, this means having a copy constructor on Address as well, since a student has an Address field.
Read Effective Java by Joshua Bloch for reasons why clone should be avoided.
public class Student {
final private String name;
final private int age;
final private Address address;
public Address getAddress() {
return address;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Student(Student copyStudent) {
this.name = new String(copyStudent.getName());
this.age = copyStudent.getAge();
this.address = new Address(copyStudent.getAddress());
}
}
From Effective Java
The copy constructor approach and its static factory variant have many
advantages over Cloneable/clone: They do not rely on a risk-prone
extralinguistic object creation mechanism; they do not demand
unenforceable adherence to ill-documented conventions; they do not
conflict with the proper use of final fields; they do not require the
client to catch an unnecessary checked exception; and they provide a
statically typed object to the client. While it is impossible to put a
copy constructor or static factory in an interface, Cloneable fails to
function as an interface because it lacks a public clone method.
Therefore you aren’t giving up interface functionality by using a copy
constructor instead of a clone method. Furthermore, a copy constructor
(or static factory) can take an argument whose type is an appropriate
interface implemented by the class. For example, all general-purpose
collection implementations, by convention, provide a copy constructor
whose argument is of type Collection or Map. Interface-based copy
constructors allow the client to choose the implementation of the
copy, rather than forcing the client to accept the implementation of
the original. For example, suppose you have a LinkedList l, and you
want to copy it as an ArrayList. The clone method does not offer this
functionality, but it’s easy with a copy constructor: new
ArrayList(l). Given all of the problems associated with Cloneable, it
is safe to say that other interfaces should not extend it and that
classes designed for inheritance (Item 15) should not implement it.
Because of its many shortcomings, some expert programmers simply
choose never to override the clone method and never to invoke it
except, perhaps, to copy arrays cheaply. Be aware that if you do not
at least provide a well-behaved protected clone method on a class
designed for inheritance, it will be impossible for subclasses to
implement Cloneable.
Student needs to implement Cloneable.
Student and Address both need 'deep' clone, if you don't want to share Address instance both in source and target Student instances:
class Student implements Cloneable {
#Override
protected Object clone() throws CloneNotSupportedException {
Student result = (Student)super.clone();
result.setAddress((Address)getAddress().clone());
return result;
}
...
}
class Address implements Cloneable{
#Override
protected Object clone() throws CloneNotSupportedException {
return (Address) super.clone();
}
...
}