Writing an object value in java [duplicate] - java

This question already has answers here:
How to create a println/print method for a custom class
(6 answers)
Closed 8 years ago.
Hello I have question to my small program how I can print the value of p1? When I am using p1.toString() method this still shows me the address of an object I was searching in google some other ways and I still don't know how to do this. Here is the code:
public class Boss {
String name;
public Boss(String input) { // This is the constructor
name = "Our Boss is also known as : " + input;
}
public static void main(String args[]) {
Boss p1 = new Boss("Super-Man");
System.out.println(p1.toString());
}

You seem to have forgotten to override toString()
// Add this to Boss
public String toString() {
return name;
}
Or (as you currently have your code),
// System.out.println(p1.toString());
System.out.println(p1.name);
You should probably add a getName() method to Boss as well,
public String getName() {
return name;
}

You need to override the toString method to get the functionality that you are expecting. Also I recommend setting the String name to private while you're at it. If you need to provide access to the String then create a get method to return it. This prevents someone from modifying it when they shouldn't have access. Not providing an access modifier in Java defaults to protected.
public class Boss {
private String name; // Change access modifier to private
public Boss(String input) {
name = "Our Boss is also known as : " + input;
}
#Override
public String toString(){ // Override the toString method
return name;
}
public static void main(String args[]) {
Boss p1 = new Boss("Super-Man");
System.out.println(p1.toString());
}
}

The default toString() method in Object prints class name # hash code. You can override toString() method in your class to print proper output.
#Override
public String toString(){
return name;
}
Sources:
http://javarevisited.blogspot.com/2012/09/override-tostring-method-java-tips-example-code.html
http://www.geeksforgeeks.org/overriding-tostring-method-in-java/

Related

In Java, what's the use of object reference returns in a method? [duplicate]

I want to achieve method chaining in Java.
How can I achieve it?
Also let me know when to use it.
public class Dialog {
public Dialog() {
}
public void setTitle(String title) {
//Logic to set title in dialog
}
public void setMessage(String message) {
//Logic to set message
}
public void setPositiveButton() {
//Logic to send button
}
}
I want to create method chaining that I can use as follows:
new Dialog().setTitle("Title1").setMessage("sample message").setPositiveButton();
or like
new Dialog().setTitle("Title1").setMessage("sample message");
or like
new Dialog().setTitle("Title1").setPositiveButton();
Have your methods return this like:
public Dialog setMessage(String message)
{
//logic to set message
return this;
}
This way, after each call to one of the methods, you'll get the same object returned so that you can call another method on.
This technique is useful when you want to call a series of methods on an object: it reduces the amount of code required to achieve that and allows you to have a single returned value after the chain of methods.
An example of reducing the amount of code required to show a dialog would be:
// Your Dialog has a method show()
// You could show a dialog like this:
new Dialog().setMessage("some message").setTitle("some title")).show();
An example of using the single returned value would be:
// In another class, you have a method showDialog(Dialog)
// Thus you can do:
showDialog(new Dialog().setMessage("some message").setTitle("some title"));
An example of using the Builder pattern that Dennis mentioned in the comment on your question:
new DialogBuilder().setMessage("some message").setTitle("some title").build().show();
The builder pattern allows you to set all parameters for a new instance of a class before the object is being built (consider classes that have final fields or objects for which setting a value after it's been built is more costly than setting it when it's constructed).
In the example above: setMessage(String), setTitle(String) belong to the DialogBuilder class and return the same instance of DialogBuilder that they're called upon; the build() method belongs to the DialogBuilder class, but returns a Dialog object the show() method belongs to the Dialog class.
Extra
This might not be related to your question, but it might help you and others that come across this question.
This works well for most use cases: all use cases that don't involve inheritance and some particular cases involving inheritance when the derived class doesn't add new methods that you want to chain together and you're not interested in using (without casting) the result of the chain of methods as an object of the derived.
If you want to have method chaining for objects of derived classes that don't have a method in their base class or you want the chain of methods to return the object as a reference of the derived class, you can have a look at the answers for this question.
Just add a static builder method, and create another set of the setter methods.
For example
class Model {
private Object FieldA;
private Object FieldB;
public static Model create() {
return new Model();
}
public Model withFieldA(Object value) {
setFieldA(value);
return this;
}
public Model withFieldB(Object value) {
setFieldB(value);
return this;
}
}
...
And use it like
Model m = Model.create().withFieldA("AAAA").withFieldB(1234);
example of reducing the amount of code required to show a dialog would be:
package com.rsa.arraytesting;
public class ExampleJavaArray {
String age;
String name;
public ExampleJavaArray getAge() {
this.age = "25";
return this;
}
public ExampleJavaArray setName(String name) {
this.name = name;
return this;
}
public void displayValue() {
System.out.println("Name:" + name + "\n\n" + "Age:" + age);
}
}
another class
package com.rsa.arraytesting;
public class MethodChaining {
public static void main(String[] args) {
ExampleJavaArray mExampleJavaArray = new ExampleJavaArray();
mExampleJavaArray.setName("chandru").getAge().displayValue();
}
}
In case if you are using lombok, you can use parameter in your lombok.config:
lombok.accessors.chain = true
Or for particular data classes you can declare #Accessors(chain = true) annotation:
import lombok.experimental.Accessors;
#Accessors(chain = true)
#Data
public class DataType {
private int value;
// will generate setter:
public DataType setValue(int value) {
this.value = value;
return this;
}
}

Why do we need to use the builder design pattern when we can do the same thing with setters? [duplicate]

This question already has answers here:
When would you use the Builder Pattern? [closed]
(13 answers)
Closed 3 years ago.
public class Employee {
private String name;
private String address;
private int id;
public Employee() {
// TODO Auto-generated constructor stub
}
#Override
public String toString() {
return "Employee [name=" + name + ", address=" + address + ", id=" + id + "]";
}
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 getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
public class Main {
public static void main(String[] args) {
Employee e = new Employee();
e.setName("Priyanka");
Employee e1 = new Employee();
e1.setName("Rahul");
e1.setAddress("Delhi");
System.out.println("Value of e :"+ e);
System.out.println("Value of e1:"+ e1);
}
}
The builder pattern can be useful to:
apply some check on the data used to initialize the object. For example if you need a double check between variables
create immutable objects. You can't change an object once initialized, so you can't use setters
add readability of code.
reduce the code used to initialize the object
have the instance in a valid state. Using setters the object instance can be in a not valid state before all the setters are called.
Note on using the builder to create immutable objects.
When you work in a multithread environment an immutable object can be shared between threads without explicit synchronization. Because the object can't change during the time is not possible to have a race condition accessing and modifying it by two threads at the same time.
There is no need to use any pattern. You can even avoid setters with making the variables public. However,
the intent of the Builder design pattern is to separate the
construction of a complex object from its representation
Source: https://en.wikipedia.org/wiki/Builder_pattern
Using a builder pattern has a few advantages:
Unlike with setters (which make your class mutable), a builder can be used to contruct immutable objects. In many cases immutable objects are preferred over mutable objects, because they are easier to understand and maintain, and because they avoid the need for locking in multithreaded environments.
A builder can make sure that the object satisfies some invariants even directly after construction. For example, if your class has a name field which must never be null, the builder can check this condition and fail to construct the object when not satisfied.
Both things you can also accomplish by using a constructor which takes all the class contents as parameters, but that will be quite unreadable when your class has more than a few fields to initialize.

Is it possible to add to a class for example a premade Java class without overriding it? [duplicate]

Is there, in Java, a way to add some fields and methods to an existing class?
What I want is that I have a class imported to my code, and I need to add some fields, derived from the existing fields, and their returning methods.
Is there any way to do this?
You can create a class that extends the one you wish to add functionality to:
public class sub extends Original{
...
}
To access any of the private variables in the superclass, if there aren't getter methods, you can change them from "private" to "protected" and be able to reference them normally.
Hope that helps!
You can extend classes in Java. For Example:
public class A {
private String name;
public A(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
public class B extends A {
private String title;
public B(String name, String title){
super(name); //calls the constructor in the parent class to initialize the name
this.title= title;
}
public String getTitle(){
return this.title;
}
public void setTitle(String title) {
this.title= title;
}
}
Now instances of B can access the public fields in A:
B b = new B("Test");
String name = b.getName();
String title = b.getTitle();
For more detailed tutorial take a look at Inheritance (The Java Tutorials > Learning the Java Language > Interfaces and Inheritance).
Edit: If class A has a constructor like:
public A (String name, String name2){
this.name = name;
this.name2 = name2;
}
then in class B you have:
public B(String name, String name2, String title){
super(name, name2); //calls the constructor in the A
this.title= title;
}
The examples only really apply if the class you're extending isn't final. For example, you cannot extend java.lang.String using this method. There are however other ways, such as using byte code injection using CGLIB, ASM or AOP.
Assuming this question is asking about the equivalent of C# extension methods or JavaScript prototypes then technically it is possible as this one thing that Groovy does a lot. Groovy compiles Java and can extend any Java class, even final ones. Groovy has metaClass to add properties and methods (prototypes) such as:
// Define new extension method
String.metaClass.goForIt = { return "hello ${delegate}" }
// Call it on a String
"Paul".goForIt() // returns "hello Paul"
// Create new property
String.metaClass.num = 123
// Use it - clever even on constants
"Paul".num // returns 123
"Paul".num = 999 // sets to 999
"fred".num // returns 123
I could explain how to do the same way as Groovy does, but maybe that would be too much for the poster. If they like, I can research and explain.

Java method appends method [duplicate]

I want to achieve method chaining in Java.
How can I achieve it?
Also let me know when to use it.
public class Dialog {
public Dialog() {
}
public void setTitle(String title) {
//Logic to set title in dialog
}
public void setMessage(String message) {
//Logic to set message
}
public void setPositiveButton() {
//Logic to send button
}
}
I want to create method chaining that I can use as follows:
new Dialog().setTitle("Title1").setMessage("sample message").setPositiveButton();
or like
new Dialog().setTitle("Title1").setMessage("sample message");
or like
new Dialog().setTitle("Title1").setPositiveButton();
Have your methods return this like:
public Dialog setMessage(String message)
{
//logic to set message
return this;
}
This way, after each call to one of the methods, you'll get the same object returned so that you can call another method on.
This technique is useful when you want to call a series of methods on an object: it reduces the amount of code required to achieve that and allows you to have a single returned value after the chain of methods.
An example of reducing the amount of code required to show a dialog would be:
// Your Dialog has a method show()
// You could show a dialog like this:
new Dialog().setMessage("some message").setTitle("some title")).show();
An example of using the single returned value would be:
// In another class, you have a method showDialog(Dialog)
// Thus you can do:
showDialog(new Dialog().setMessage("some message").setTitle("some title"));
An example of using the Builder pattern that Dennis mentioned in the comment on your question:
new DialogBuilder().setMessage("some message").setTitle("some title").build().show();
The builder pattern allows you to set all parameters for a new instance of a class before the object is being built (consider classes that have final fields or objects for which setting a value after it's been built is more costly than setting it when it's constructed).
In the example above: setMessage(String), setTitle(String) belong to the DialogBuilder class and return the same instance of DialogBuilder that they're called upon; the build() method belongs to the DialogBuilder class, but returns a Dialog object the show() method belongs to the Dialog class.
Extra
This might not be related to your question, but it might help you and others that come across this question.
This works well for most use cases: all use cases that don't involve inheritance and some particular cases involving inheritance when the derived class doesn't add new methods that you want to chain together and you're not interested in using (without casting) the result of the chain of methods as an object of the derived.
If you want to have method chaining for objects of derived classes that don't have a method in their base class or you want the chain of methods to return the object as a reference of the derived class, you can have a look at the answers for this question.
Just add a static builder method, and create another set of the setter methods.
For example
class Model {
private Object FieldA;
private Object FieldB;
public static Model create() {
return new Model();
}
public Model withFieldA(Object value) {
setFieldA(value);
return this;
}
public Model withFieldB(Object value) {
setFieldB(value);
return this;
}
}
...
And use it like
Model m = Model.create().withFieldA("AAAA").withFieldB(1234);
example of reducing the amount of code required to show a dialog would be:
package com.rsa.arraytesting;
public class ExampleJavaArray {
String age;
String name;
public ExampleJavaArray getAge() {
this.age = "25";
return this;
}
public ExampleJavaArray setName(String name) {
this.name = name;
return this;
}
public void displayValue() {
System.out.println("Name:" + name + "\n\n" + "Age:" + age);
}
}
another class
package com.rsa.arraytesting;
public class MethodChaining {
public static void main(String[] args) {
ExampleJavaArray mExampleJavaArray = new ExampleJavaArray();
mExampleJavaArray.setName("chandru").getAge().displayValue();
}
}
In case if you are using lombok, you can use parameter in your lombok.config:
lombok.accessors.chain = true
Or for particular data classes you can declare #Accessors(chain = true) annotation:
import lombok.experimental.Accessors;
#Accessors(chain = true)
#Data
public class DataType {
private int value;
// will generate setter:
public DataType setValue(int value) {
this.value = value;
return this;
}
}

How to do method chaining in Java? o.m1().m2().m3().m4()

I've seen in many Java code notation that after a method we call another, here is an example.
Toast.makeText(text).setGravity(Gravity.TOP, 0, 0).setView(layout).show();
As you see after calling makeText on the return we call setGravity and so far
How can I do this with my own classes? Do I have to do anything special?
This pattern is called "Fluent Interfaces" (see Wikipedia)
Just return this; from the methods instead of returning nothing.
So for example
public void makeText(String text) {
this.text = text;
}
would become
public Toast makeText(String text) {
this.text = text;
return this;
}
class PersonMethodChaining {
private String name;
private int age;
// In addition to having the side-effect of setting the attributes in question,
// the setters return "this" (the current Person object) to allow for further chained method calls.
public PersonMethodChaining setName(String name) {
this.name = name;
return this;
}
public PersonMethodChaining setAge(int age) {
this.age = age;
return this;
}
public void introduce() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
// Usage:
public static void main(String[] args) {
PersonMethodChaining person = new PersonMethodChaining();
// Output: Hello, my name is Peter and I am 21 years old.
person.setName("Peter").setAge(21).introduce();
}
}
Without method chaining
class Person {
private String name;
private int age;
// Per normal Java style, the setters return void.
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void introduce() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
// Usage:
public static void main(String[] args) {
Person person = new Person();
// Not using chaining; longer than the chained version above.
// Output: Hello, my name is Peter and I am 21 years old.
person.setName("Peter");
person.setAge(21);
person.introduce();
}
}
Method chaining, also known as named parameter idiom, is a common syntax for invoking multiple method calls in object-oriented programming languages. Each method returns an object, allowing the calls to be chained together in a single statement. Chaining is syntactic sugar which eliminates the need for intermediate variables. A method chain is also known as a train wreck due to the increase in the number of methods that come one after another in the same line that occurs as more methods are chained together even though line breaks are often added between methods.
A similar syntax is method cascading, where after the method call the expression evaluates to the current object, not the return value of the method. Cascading can be implemented using method chaining by having the method return the current object itself (this). Cascading is a key technique in fluent interfaces, and since chaining is widely implemented in object-oriented languages while cascading isn't, this form of "cascading-by-chaining by returning this" is often referred to simply as "chaining". Both chaining and cascading come from the Smalltalk language.
From your example:
Toast.makeText(text).setGravity(Gravity.TOP, 0, 0).setView(layout).show();
Each method in the chain has to return a class or an interface. The next method in the chain has to be a part of the returned class.
We start with Toast. The method makeText, which is defined as a static method in the class Toast, has to return a class or an interface. Here, it returns an instance of the class Gravity.
The method setGravity, which is defined in the class Gravity, returns an instance of the class View,
The method setView, which is defined in the class View, returns an instance of the class JPanel.
This chain could be written out step by step.
Gravity gravity = Toast.makeText(text);
View view = gravity.setGravity(Gravity.TOP, 0, 0);
JPanel panel = view.setView(layout);
panel.show();
Writing the chain as a chain removes all of the intermediate instance variables from the source code.
Search for builder pattern or fluent interface on google to have more details about this.
Return 'this' at the end of your method can do the trick in most cases.
Adding return this; would surely help in chaining for this class but fail for sub-classes.
If you want to have the chaining behaviour inherited to the sub-classes also then change your class signature as below:
Class SuperClass < SubClass extends SuperClass >{}
This way all sub-classes will inherit method chaining.
Example:
public class SuperClass<SubClass extends SuperClass> {
public SubClass testMethod(){
return (SubClass)this;
}
public static void main(String[] args) {
SuperClass<SuperClass> superClass = new SuperClass<SuperClass>();
superClass.testMethod().testMethod().testMethod();
System.out.println(superClass.toString());
}
}
or you can use Diezel that generates all the interfaces you need based on a Regular expression of your fluent API.

Categories

Resources