Default Get method in custom java class - java

java n00b here.
I have a custom Data type defined like this:
public class MyData{
int value;
int type;
String name;
public MyData(int newValue, int newType, string newName)
{
value = newValue;
type = newType;
name = newName;
}
}
When I call an instance of this class, I want it to evaluate to the value property, like this:
myData dataInstance = new myData(100,3,"customData");
System.out.println(dataInstance); // should print "100"
Can this be achieved?

When you use System.out.println with an object, it's going to call the toString() method - so you just need to override that:
#Override public String toString() {
return String.valueOf(value);
}
Also note that you should be more specific in your terminology. When you wrote:
When I call an instance of this class
... that doesn't mean anything. You don't call an instance - you call a method on an instance. In this case, the method is toString.

Related

Determine if the object is a parameter of System.out.print/println methods

in my class SampleClass, I want it to perform such operation: when an instance of SampleClass is included as a parameter of the System.out.print() or System.out.println() method, the object automatically calls its own To_String() method.
public class SampleClass{
private int count;
public SampleClass(){
// maybe do something here?
}
private String To_String(){
return Integer.toString(count);
}
}
so that when I do
SampleClass s = new SampleClass();
System.out.println(s);
Can automatically print out the value of s.count field as a string, instead of having to do System.out.println(s.To_String()). Thank you.
You can't do that, but if the visibility is public you can override Object.toString() instead like
#Override
public String toString() {
return Integer.toString(count);
}
And then System.out.println(s); will work as you describe.
You can override toString() method which will be automatically called when you do System.out.println(sampleObject).
public class SampleClass {
private int count;
public SampleClass(){
// maybe do something here?
}
#Override
public String toString(){
return Integer.toString(count);
}
}
then
SampleClass s = new SampleClass();
System.out.println(s);
will work as expected.
If you read the documentation of println(Object x), it says:
Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().
If you then read the documentation of String.valueOf(Object obj), it says:
Returns: if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
This means that System.out.println(s), for a non-null s Object, is the same as:
System.out.print(s.toString());
System.out.println();
All you have to do, is implement the toString() method inherited from Object in your class:
#Override
public String toString() {
return Integer.toString(count);
}
Or, if you insist on using your own To_String() method:
#Override
public String toString() {
return To_String();
}

How can I refer the objcet that calls a method in the method in Java? [duplicate]

This question already has answers here:
When should I use "this" in a class?
(17 answers)
Closed 7 years ago.
I'm trying to get an understanding of what the the java keyword this actually does.
I've been reading Sun's documentation but I'm still fuzzy on what this actually does.
The this keyword is a reference to the current object.
class Foo
{
private int bar;
public Foo(int bar)
{
// the "this" keyword allows you to specify that
// you mean "this type" and reference the members
// of this type - in this instance it is allowing
// you to disambiguate between the private member
// "bar" and the parameter "bar" passed into the
// constructor
this.bar = bar;
}
}
Another way to think about it is that the this keyword is like a personal pronoun that you use to reference yourself. Other languages have different words for the same concept. VB uses Me and the Python convention (as Python does not use a keyword, simply an implicit parameter to each method) is to use self.
If you were to reference objects that are intrinsically yours you would say something like this:
My arm or my leg
Think of this as just a way for a type to say "my". So a psuedocode representation would look like this:
class Foo
{
private int bar;
public Foo(int bar)
{
my.bar = bar;
}
}
The keyword this can mean different things in different contexts, that's probably the source of your confusion.
It can be used as a object reference which refers to the instance the current method was called on: return this;
It can be used as a object reference which refers to the instance the current constructor is creating, e.g. to access hidden fields:
MyClass(String name)
{
this.name = name;
}
It can be used to invoke a different constructor of a a class from within a constructor:
MyClass()
{
this("default name");
}
It can be used to access enclosing instances from within a nested class:
public class MyClass
{
String name;
public class MyClass
{
String name;
public String getOuterName()
{
return MyClass.this.name;
}
}
}
"this" is a reference to the current object.
See details here
The keyword this is a reference to the current object. It's best explained with the following piece of code:
public class MyClass {
public void testingThis()
{
// You can access the stuff below by
// using this (although this is not mandatory)
System.out.println(this.myInt);
System.out.println(this.myStringMethod());
// Will print out:
// 100
// Hello World
}
int myInt = 100;
string myStringMethod()
{
return "Hello World";
}
}
It's not used a lot unless you have code standard at your place telling you to use the this keyword. There is one common use for it, and that's if you follow a code convention where you have parameter names that are the same as your class attributes:
public class ProperExample {
private int numberOfExamples;
public ProperExample(int numberOfExamples)
{
this.numberOfExamples = numberOfExamples;
}
}
One proper use of the this keyword is to chain constructors (making constructing object consistent throughout constructors):
public class Square {
public Square()
{
this(0, 0);
}
public Square(int x_and_y)
{
this(x_and_y, x_and_y);
}
public Square(int x, int y)
{
// finally do something with x and y
}
}
This keyword works the same way in e.g. C#.
An even better use of this
public class Blah implements Foo {
public Foo getFoo() {
return this;
}
}
It allows you to specifically "this" object in the current context. Another example:
public class Blah {
public void process(Foo foo) {
foo.setBar(this);
}
}
How else could you do these operations.
"this" keyword refers to current object due to which the method is under execution. It is also used to avoid ambiguity between local variable passed as a argument in a method and instance variable whenever instance variable and local variable has a same name.
Example ::
public class ThisDemo1
{
public static void main(String[] args)
{
A a1=new A(4,5);
}
}
class A
{
int num1;
int num2;
A(int num1)
{
this.num1=num1; //here "this" refers to instance variable num1.
//"this" avoids ambigutiy between local variable "num1" & instance variable "num1"
System.out.println("num1 :: "+(this.num1));
}
A(int num, int num2)
{
this(num); //here "this" calls 1 argument constructor within the same class.
this.num2=num2;
System.out.println("num2 :: "+(this.num2));
//Above line prints value of the instance variable num2.
}
}
The keyword 'this' refers to the current object's context. In many cases (as Andrew points out), you'll use an explicit this to make it clear that you're referring to the current object.
Also, from 'this and super':
*There are other uses for this. Sometimes, when you are writing an instance method, you need to pass the object that contains the method to a subroutine, as an actual parameter. In that case, you can use this as the actual parameter. For example, if you wanted to print out a string representation of the object, you could say "System.out.println(this);". Or you could assign the value of this to another variable in an assignment statement.
In fact, you can do anything with this that you could do with any other variable, except change its value.*
That site also refers to the related concept of 'super', which may prove to be helpful in understanding how these work with inheritance.
It's a reference of actual instance of a class inside a method of the same class.
coding
public class A{
int attr=10;
public int calc(){
return this.getA()+10;
}
/**
*get and set
**/
}//end class A
In calc() body, the software runs a method inside the object allocated currently.
How it's possible that the behaviour of the object can see itself? With the this keyword, exactly.
Really, the this keyword not requires a obligatory use (as super) because the JVM knows where call a method in the memory area, but in my opinion this make the code more readeable.
It can be also a way to access information on the current context.
For example:
public class OuterClass
{
public static void main(String[] args)
{
OuterClass oc = new OuterClass();
}
OuterClass()
{
InnerClass ic = new InnerClass(this);
}
class InnerClass
{
InnerClass(OuterClass oc)
{
System.out.println("Enclosing class: " + oc + " / " + oc.getClass());
System.out.println("This class: " + this + " / " + this.getClass());
System.out.println("Parent of this class: " + this.getClass().getEnclosingClass());
System.out.println("Other way to parent: " + OuterClass.this);
}
}
}
Think of it in terms of english, "this object" is the object you currently have.
WindowMaker foo = new WindowMaker(this);
For example, you are currently inside a class that extends from the JFrame and you want to pass a reference to the WindowMaker object for the JFrame so it can interact with the JFrame. You can pass a reference to the JFrame, by passing its reference to the object which is called "this".
Every object can access a reference to itself with keyword this (sometimes called the this
reference).
First lets take a look on code
public class Employee {
private int empId;
private String name;
public int getEmpId() {
return this.empId;
}
public String getName() {
return this.name;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public void setName(String name) {
this.name = name;
}
}
In the above method getName() return instance variable name.
Now lets take another look of similar code is
public class Employee {
private int empId;
private String name;
public int getEmpId() {
return this.empId;
}
public String getName() {
String name="Yasir Shabbir";
return name;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public void setName(String name) {
this.name = name;
}
public static void main(String []args){
Employee e=new Employee();
e.setName("Programmer of UOS");
System.out.println(e.getName());
}
}
Output
Yasir Shabbir
this operator always work with instance variable(Belong to Object)
not any class variable(Belong to Class)
this always refer to class non static attribute not any other parameter or local variable.
this always use in non static method
this operator cannot work on static variable(Class variable)
**NOTE:**It’s often a logic error when a method contains a parameter or local variable that has the
same name as a field of the class. In this case, use reference this if you wish to access the
field of the class—otherwise, the method parameter or local variable will be referenced.
What 'this' does is very simply. It holds the reference of current
object.
This keyword holds the reference of instance of current class
This keyword can not be used inside static function or static blocks
This keyword can be used to access shadowed variable of instance
This keyword can be used to pass current object as parameter in function calls
This keyword can be used to create constructor chain
Source: http://javaandme.com/core-java/this-word

Java function on function [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 use constructors in java, android?

I have a short question about the following code from
http://www.androidhive.info/2013/09/android-sqlite-database-with-multiple-tables/
Here are used two Constructors, one with the id, and the other without - I don't understand why. What's the benefit?
I already read this thread:
Why does this class have two constructors?
The answer I could understand is, that I can create a Tag with id and not, but I'm trying to understand, how to know which constructor it shall use? Is it just by the number of parameters?
public class Tag {
int id;
String tag_name;
// constructors
public Tag() {
}
public Tag(String tag_name) {
this.tag_name = tag_name;
}
public Tag(int id, String tag_name) {
this.id = id;
this.tag_name = tag_name;
}
// ...
}
Yes, only by its amount of parameters.
It's called "overloading" of functions. You can overload a function by providing the same signature with different parameters (according to their type and order).
The JVM will then decide which method to use in a certain situation.
Please note:
If you provide a constructor the JVM won't provide a default constructor any more.
class Foo{
private int x;
private String name;
Foo(int x){ //constructor 1
this(x, "Default Name");
}
Foo(String name){ //constructor 2
this(0, name);
}
Foo(int x, String name){ //constructor 3
this.x = x;
this.name = name;
}
}
Foo f1 = new Foo(9); //calls constructor 1, who will call constructor 3
//f1.x = 9, f1.name = "Default Name"
Foo f2 = new Foo("Test"); // calls constructor 2, who will call constructor 3
// f2.x = 0; f2.name = "Test"
Foo f3 = new Foo(3, "John"); //calls constructor 3
// f3.x = 3; f3.name = "John"
Foo f4 = new Foo() // This won't work! No default Constructor provided!
**which constructor it shall use? only of its amount of paremeters?
**
Yes, for example If you call
Tag newTag = new Tag();
it will call
public Tag() {
}
but if you call
Tag newTag = new Tag("Name");
it will call
public Tag(String tag_name) {
}
and so on
by how many arguments you pass to the constructor that way it will know which one to call
The compiler knows "which constructor it shall use" by a rule, in the Java Language Specification.
A resume:
Is by signature of the method (the type and order of arguments --- the exceptions dont effect the signature, and the return type too). This is not restricted only by the constructor, but any method, properly Overloaded; You can study these by topic of "Overloading". The reason to Overload a method --- or a constructor too ---, is to give more flexibility.

Method Overloading; Naming Helper Method

I like creating public helpers for private members when creating functions. I made a public helper
public void create(String key, String value) { ... }
for a private member
private void create(String key, String value) { ... }
Now, I am overloading the private member and know I need to do so in Java by
Method signature (type or quantity)
and I am unable to overload by return type. Thus, I decide to modify my private member to accept a boolean argument.
private void create(String key, String value, boolean status) { ... }
I admit this parameter is not one I plan to use or consider. Have I become complacent to accept poor coding behavior?
The public helper merely calls the private member passing supplied arguments
public void create(String key, String value) { create(key, value, true); }
While a helper class might be a quick solution, you are still coupling the implementation to the classes you are exposing (the "caller" class). Interfaces were created to create the abstraction you intend to create (i.e. hiding private implementation from public view) but the added flexibility that:
Could be used by other classes wanting to have their own implementations of similar behaviour
De-couples the implementation from the calling class.
At run-time you could choose which implementation to use (via IoC or similar)
Here's my suggestion:
MyObjectImpl.java -> implements MyObject.java
private Object createObjectNotInitialized( String name ){
return new Object();
}
private Object createObjectInitialized( String name ){
Object newObj = new Object();
newObj.setName( name );
return newObj;
}
public Object createObject( String name, boolean doInit ){
if( doInit ){
return createObjectInitialized(name);
}else{
return createObjectNotInitialized(name);
}
}
// you can chose to init objects by default - I chose not to for this example
public Object createObject( String name ){
return createObjectNotInitialized(name);
}
MyObject.java -> Interface
Object createObject( String name, boolean doInit );
Object createObject( String name );
Caller.java Calling Class
MyObject myObj = new MyObjectImpl();
Object o = myObj.createObject( "Hello" );

Categories