What is the use of Java virtual method invocation? [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I understand what is java method invocation and have practiced many examples using it.
I want to know what is the practical situation or need of this concept.
It would be of great help if anyone could give a real world scenario where it is used and
what would happen if this concept would have not been there?

Here is an example. Suppose we have 2 classes:
class A {
public String getName() {
return "A";
}
}
class B extends A {
public String getName() {
return "B";
}
}
If we now do the following:
public static void main(String[] args) {
A myA = new B();
System.out.println(myA.getName());
}
we get the result
B
If Java didn't have virtual method invocation, it would determine at compile time that the getName() to be called is the one that belongs to the A class. Since it doesn't, but determines this at runtime depending on the actual class that myA points to, we get the above result.
[EDIT to add (slightly contrived) example]
You could use this feature to write a method that takes any number of Objects as argument and prints them like this:
public void printObjects(Object... objects) {
for (Object o: objects) {
System.out.println(o.toString());
}
}
This will work for any mix of Objects. If Java didn't have virtual method invocation, all Objects would be printed using Object´s toString() which isn't very readable. Now instead, the toString() of each actual class will be used, meaning that the printout will usually be much more readable.

OK, I'll try to provide a simple example. You are writing a method that will fill a caller-supplied list:
public void fill(List l) {
list.add("I just filled the list!");
}
Now, one caller wants to use a linked list; another one prefers a list implementation based on an array. There will be other callers with even more list implementations that you've never even heard of. These are totally different objects. Propose a solution that achieves this without relying on virtual methods.
Without virtual methods this would mean that the type List would already need to have the method add implemented. Even if you had a subtype ArrayList which had an overridden method, the compiler (and the runtime!) would simply ignore that method and use the one in List. It would be impossible to use different List implementations that conform to the same interface; it would be impossible to reuse that line of code in the method fill since it would work only with the method in the type List.
So you see, the whole idea of type hierarchy wouldn't make a lot of sense; interfaces and abstract classes couldn't even exist. The whole of Java would break down into shards without that one feature of virtual methods.

Related

Java: What does "a method trails another method" really means? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have met the text "doSomethind() method is modiffied to trail another method", and it is not very clear to me what does this means?
Does it means that it is calling the "another method"?
Does it means it is overwriting or overridding the "another method"?
Does it means that it is called by the "another method"?
I am really confused.
"Method trailing" is not a defined term in Computer Science or Java. It appears that the person who wrote this text is using their own private terminology. You should ask them to find out.
My personal speculation would conclude in that:
The author means that the method is placed before another method in the source code; or
The author is refering to Method chaining
"If doSomethings(), that has no exception handling code, trails a method that throws an exception, what will make the code to compile?"
"Trails" could mean anything. I would have assumed it just means it appears after another method in the class file, but I assume the author had something else in mind.
"no exception handling code" This doesn't imply anything at all. In the code below, there is no exception handling code and it compiles fine.
There is nothing in the quote which suggests you need to do anything special to write a method which compiles.
Warning: some web sites (rose india comes to mind) have lots of written material which is technically confused and shouldn't be read too closely, if at all. They are like a lot of marketing, nice on the surface, but the more you think about them, the less sense they make ;)
Say you have code like this
public void a() {
b();
}
public void b() {
c();
}
Does it means that it is calling the "another method"?
Method b is calling another method named c
Does it means it is overwriting or overridding the "another method"?
Overriding means it overrides a method defining in a parent class instead of inheriting it.
Overwriting is something you can do to a file, but not a method.
Does it means that it is called by the "another method"?
Method b is called by another method nameda
It looks like a case of Method Chaining:
public class SomeClass {
public SomeClass method1() {
// code here
return this;
}
public SomeClass method2() {
// code here
return this;
}
}
Usage:
SomeClass someObj = new SomeClass();
someObj.method1().method2();
This pattern is a somewhat niche one but it appears in many places (like Query frameworks) or used together with other patterns (like the Builder pattern).
There is no overriding/overloading in either case and they are not calling each other either.

Use of overloading vs overriding, compile time vs run time [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Effective:The choice of which overloading to invoke is made at compile time.
Example:
class parentsecond{
public int getdouble(int x){ return x*2;}
}
class second extends parentsecond{
public int getdouble(int x){ return x*3;}
}
class third{
public static void calloverload(parentsecond s){
System.out.println(s.getdouble(4));
}
public static void calloverload(second s){
System.out.println(s.getdouble(4));
}
public static void main(String[] args){
third t=new third();
parentsecond s=new second();
t.calloverload(s);
}
}
Answer is 12.
And the behaviour is the same for instance method overloaded method too.
So in either case ,the decision of which overloaded method is invoked is made at run-time rather than compile time(its always 'second's' getdouble which is invoked).
So there are some qualifications to this particular item in 'Effective Java' that I did not get.
Please help clarify what was meant by 'resolving overloading at compile-time'.
How is the above different from this:
....
class fourth{
public static String getCollection(Set<?> s){
return "Set";
}
public static String getCollection(Collection<?> c){
return "Collection";
}
public String getiCollection(Set<?> s){
return "Set";
}
public String getiCollection(Collection<?> c){
return "Collection";
}
public static void main(String[] args){
Collection<String> c=new HashSet<String>();
System.out.println(fourth.getCollection(c));
fourth f=new fourth();
System.out.println(f.getiCollection(c));
...
This answer in this case is always 'Collection' rather than the actual run-time type.
The declared type of s is parentsecond so when the compiler runs through the code, it will assign the method that takes parentsecond as an argument
public static void calloverload(parentsecond s)...
However, overriding is a different subject. The actual type of the instance s is second and so second's getdouble method will be executed. This is a case of polymorphism. In java, polymorphism is accomplished through late-binding.
To quote from this answer:
The JLS states in §8.4.9 Overloading:
When a method is invoked (§15.12), the number of actual arguments (and any explicit type arguments) and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked (§15.12.2).
If the method that is to be invoked is an instance method, the actual method to be invoked will be determined at run time, using dynamic method lookup (§15.12.4).
The argument is s and its compile time type is parentsecond. Its run time type is second.
EDIT To answer the addition to your question, see point 1 above. Nothing needs to be evaluated at run time. The compiler uses the compile time type, Collection, in both calls.
The point is not that the compiler can't figure it out; the point is that overloading is confusing for the programmer, and is therefore likely to cause bugs.
If you need to pull out the JLS in order to figure out which method is the most specific match to the way you are calling it, then every maintenance programmer who ever looks at that code will have to go through the same exercise.
Hence, the suggestion that overloads should have different numbers of parameters, or at least parameter types that are not interconvertible.
The specific danger of "resolving overloading at compile time" is this. Suppose I have:
void method(List a) { }
void method(Collection a) { }
Then, these two calls will do different things:
List list = new ArrayList();
method(list);
method((Collection)list);
This is highly unintuitive (hence confusing, hence a source of bugs) for the programmer.

What Is “the Interface” And How Do I Program “Against” It? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
ArrayList<Class> name = new ArrayList<Class>(#)
Someone told me yesterday that something like this is bad practice, and that I should program “against the interface”, like this:
List<Class> name = new ArrayList<Class>(#)
What did he mean?
ArrayList implements List. So, best to use List for a number of reasons. For example, if you wish to change the type of list (e.g. you decide to use a LinkedList, Stack, or Vector) in the future, you need only change the right side of the assignment and the rest of the code just works, unchanged.
There is no need to reveal what exact implementation of List you're using.
The only methods that are available to you are the methods from the interface. Technically it doesn't matter a lot, but it's a good habit to follow. The code is cleaner and easier to maintain.
The "interface" in that code snippet is List being a more abstract class than ArrayList.
List will be implemented by a number of other classes like ArrayList, LinkedList etc...
By using the interface to declare name, then the users of name do not have to know which type of list name actually is, and if you decide to use a different type of List in future you can without having to change lots of places within your code.
List<Class> name = new ArrayList<Class>(#)
SuperType ref = SubTypeObj
This is polymorphic way of creating an ArrayList. List is a super type of ArrayList.
The advantage of creating the arraylist like this is:
you could later refer the same list to create a LinkedList.
name = new LinkedList(#)
Ideally, you want to use the interface of a collection rather than the implementation for Collection variables and return values. In your example, it's not that big an issue. Where it does become more useful is when writing methods:
public List<String> doSomething() {
}
By using List<String> and not ArrayList<String>, this method could choose a different list to use (it might change to LinkedList for example), but the contract of the API wouldn't change, so all the calling code would still work, even though the method now returns a different type of List.
In Interface defines what methods are available, so when a class is written to implement an interface, it must have the methods defined in the interface. (it may have other methods as well)
Suppose you write a class which other people will use, and it has a method like this:
public void doSomething(List<Thing> aListOfThings) {
//some code to manipulate the list
}
When other people write code to use your class, you don't care exactly what type of List they've used to call your method. All of these are valid:
yourClass.doSomething(new ArrayList<Thing>());
yourClass.doSomething(new AttributeList<Thing>());
yourClass.doSomething(new Vector<Thing>());
yourClass.doSomething(new SomeOtherTypeOfList<Thing>());
They are free to choose whatever type (implementation) of list is suitable for their purposes.
He meant that you should use only the very type of the variable you need. For example, unless you are using methods that are only defined on ArrayList then you should use List. Likewise, if you don't need anything that comes from List then use Collection etc.
There are two reasons for this:
1) It makes it easier in the future to change the implementation to another type. Lets say you are using some ORM that uses a LazilyLoadedList, well if all your code is against List then you can slot it in painlessly. If it is against ArrayList then you need to change lots of method signatures and make sure that you aren't depending on a ArrayList specific methods. This is part of what
2) Interfaces are easier to mock using tools like JMock or Mockito.
This should help you understand what an interface is and how it is useful in software development.
Let's say you need to mail a package to someone. There are many carrier options: USPS, UPS, FedEx, etc.
Now imagine if there was one , central mailbox you could drop your package into and all carriers could deliver from that mailbox. So, you don't care how it gets picked up by USPS, UPS or FedEx. All you need to do is bring your package to the mailbox and drop it off. How it actually gets delivered is irrelevant to you.
In this example, you could have an interface defined as:
public interface IMailService
{
void SendMail(obj myMailObj);
}
And then you could have concrete implementations of MailService defined as:
public class USPSMailService : IMailService
{
public void SendMail(obj myMailObj)
{
//This code executes SendMail using USPS' implementation
}
}
public class UPSMailService : IMailService
{
public void SendMail(obj myMailObj)
{
//This code executes SendMail using UPS' implementation
}
}
public class FedExMailService : IMailService
{
public void SendMail(obj myMailObj)
{
//This code executes SendMail using FedEx's implementation
}
}
Then, when you want to send mail in your code, you would write it like this:
IMailService mailService = new FedExMailService();
mailService.SendMail(myMailObj);
If you later need to use UPS' mail service, then all you'd need to do is instantiate with the UPS type. The rest of the code, including all calls to SendMail() remain unchanged:
mailService = new UPSMailService();
Now, if UPS offers some service that the other carriers do not, then you would need to define the variable as the concrete type.
For example, if the UPS class was defined as such:
public class UPSMailService : IMailService
{
public void SendMail(obj myMailObj)
{
//This code executes SendMail using UPS' implementation
}
//This is a method that only UPS offers
public void SendMailOnSunday(obj myMailObj)
{
//This code executes UPS' proprietary method
}
}
Then your code would need to use the concrete class as such:
UPSMailService mailService = new UPSMailService();
mailService.SendMailOnSunday(myMailObj);

Set, Get and Constructors in Java

Despite Java tutorials, Wikipedia searches, stackoverflow trolling, and hours of reading code samples, constructors still confuse the crap out of me. I've got three related questions that I've been trying to answer to help ME understand constructors a little better.
First, I've been under the impression that constructors need to be named the same as their classes. Consider:
public class Money {
public Money(long l) {
this.value = l;
}
public Money(String s) {
this.value = toLong(s);
}
public long getLong() {
return this.value;
}
public String getString() {
return toString(this.value);
}
}
I see this as four constructors...correct? So it appears that constructors not named the same as the class which contains them allowable. Can someone confirm that?
Second, I seem to have a block against understanding the set and get methods. Consider:
public class GetSetSample {
public int getFoo() {
return int Foo;
}
public void setFoo(int fooValue) {
int Foo = fooValue;
}
}
Why can't I just do this:
public class getFoo(int fooValue){
foo=fooValue;
}
and use foo = getFoo(12) from some other class/method?
The third question is a little more esoteric, but will help me conceive of the bigger picture...which is my learning style, and conducive to my ability to trace program flow when debugging. The get and set methods suggest a "to" and "from" relationship to me. e.g., Passing a value "to" a constructor, receiving the result "from" the get method. It seems to me though that the "to" and "from" will change depending on your perspective. I think that any setMethod is setting parameters for an object, even though the variable comes FROM another class or method, and the GetMethod is getting the resulting object (say, this.foo) with the appropriately set parameter. No matter where the get or set is used, in a main method or a standalone class with a single constructor, 'set' is always associated with sending a parameter and get is always associated with receiving an object with that parameter. Is that a good understanding? or am I missing a vital part?
Question 1:
I see this as four constructors...correct?
No, that class has two constructors and two methods. (getLong and getString are the methods.)
Question 2:
Why can't I just do this:
public class getFoo(int fooValue){
foo=fooValue;
}
Well, that's trying to declare a class with parameters, and also you're setting a value in a get method, which would be extremely weird. It's not clear what you're trying to achieve here, but that code is thoroughly invalid.
Question 3:
The get and set methods suggest a "to" and "from" relationship to me.
Well it's not really a relationship IMO. A relationship suggests something longer term than either of these methods. A setter typically changes the state of an object in some way, and a getter typically just returns some aspect of the state of an object. It's not really clear what the rest of your explanation meant, because you're playing somewhat fast and loose with terminology. For example: "get is always associated with receiving an object with that parameter" doesn't really make sense to me. Objects don't have parameters, methods/constructors do - and getters can fetch primitive values or references...
I suspect you would benefit from reading the "Classes" part of the Java tutorial, which talks about constructors and methods.
Regarding the first answer, there's only 2 constructors. The difference is on how they are going to be called (called using a string will use the construction having a string has a parameter and called using a long will use the other one). So to answer, yes a constructor has the same name as the class.
The two constructors :
public Money(long l) {
this.value = l;
}
public Money(String s) {
this.value = toLong(s);
}
Regarding the second answer, getters ans setters are not meant to be classes. They are supposed to be within the class itself.
Consider this example which uses getter and setters to get ans set value for the printer class :
public class Printer {
#Inject #Informal Greeting greeting;
private String name;
private String salutation;
public void createSalutation() {
this.salutation = greeting.greet(name);
}
public String getSalutation() {
return salutation;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
A good read of this link could definitly help you out !
Java oriented-object principles
You've shown 2 constructors, which do need to have the same name as the class.
You've also shown two "getter" methods, which return the value of the class variable in the form requested by the user. You can also create "setter" methods, which are used to transfer values into class variables.
You use a constructor to create an object of a particular class, and optionally to set some or all of its internal state (that is, its member variables).
You use setters and getters to isolate the class variables from the outside world, so you don't need to allow other code to access them directly. Why? Because, before a setter updates a variable, it can verify that the new value is valid, and that the operation doesn't violate any or the rules (the "business logic") that are required for the class to work properly.
So you could add a setter and update the constructor to use it:
public Money(long l) {
setValue(l);
}
public Money(String s) {
setValue(toLong(s));
}
// Example setter that validates `l` by prohibiting negative values
public Money setValue(long l) {
if (l < 0) {
// Warn about negative values
}
this.value = l;
return this; // Return the current object to allow chaining; see below.
}
Note that a setter usually doesn't need to return a value (that is, it can be type void), but it's often helpful to return the object itself. That allows you to write code like this:
Money earnings = new Money().setValue(4).setOtherField("foo");
This creates an object of type Money, sets various attributes, and stores it in the variable earnings. Clearly, this isn't terribly useful for a simple class like this, but it can be very helpful for more complex classes:
Paycheck check = new Paycheck("MyCompany")
.setEmployee("YourName")
.setSalary(50,000)
.setPaySchedule(Schedule.BIWEEKLY)
.setAccountNumber("1234567")
.setDefaultTaxRate();
I would like to try to answer your implied conceptual questions -- you've already got plenty of examples of this and that, so I'm just going to try to explain. I have no doubt you have heard most of this -- maybe all of this -- before, but am not sure and not sure which parts.
Object-oriented programming centers mostly around objects; an object is an amalgamation of code and data. You define objects by writing a class, and you create one or more copies of the object defined by that class with the class constructor (called instantiating the class).
A parallel in other languages: you can have a data structure of related items and a set of subroutines that operate on that data structure. Think of a class as a way of collecting the items in that data structure and the subroutines that operate on it into one unit.
After you have invoked a constructor, you have a copy of the data defined in that class and a way to refer to that copy. By referring to that instance when you invoke a class method, you operate on that copy of the data with the methods defined in that class.
If you were to do this in a non-OO language, you could have a routine that created a copy of the data structure in memory and then only use the methods prescribed for it on that data structure. You could have a pointer to the copy in memory and pass that pointer as a parameter to every subroutine that operated on it, and in fact that's the way some pre-OO systems were programmed.
A constructor is similar to a method call that returns a value; it involves (or can involve) the execution of statements, and it always returns an object of that class. There are also differences between a constructor and a method; until the constructor completes, for instance, the object is not fully created and shouldn't have some methods invoked on it.
So I hope that helped; if there are conceptual things you still have questions about, perhaps something in here will help you form a specific question so we can explain things further.
Many people have found that if they have spent years learning languages such as COBOL and FORTRAN then changing to OO programming involves unlearning the old languages. I certainly found this when I first tackled C++ 20 years ago. From your description you are clearly struggling with the concepts and I sympathize.
I don't think there is a simple recipe. Practice at the simple examples and don't be disheartened. Don't be afraid to ask on SO - if the questions are clearly asked you will get a useful answer.
Get a good IDE (Eclipse, Netbeans, etc.) which allows you to "look inside" objects with the debugger. Hopefully at some stage things will click!
Question 1 - Basic Java Classes:
There's pretty much only 3 things you're going to find in a Java class
Field/attribute (Depending on your language of origin)
Method
Constructor (Which looks like a special kind of method)
Every class is going to have a class name that shares the name of the file it's located in. So to expand Money out a bit:
Money.java
----------
public class Money {
// This is a field/attribute
Long value;
// This is a constructor
public Money() {
this.value = Long(0L);
}
// This is a method
public Long getValue() {
return value;
}
// Another method
public void makeMoney(Long moreMoney) {
this.value = this.value + moreMoney;
}
} // Everything in here is part of the Money class
The only distinction between a constructor and a method is that a constructor has no specified return value, which is declared as a type right before the name of a potential method. Constructors do have to be named the same as the class they are contained in, but why is implied in how they are written.
Another way of looking at it is if you remove all of the non-type related Java keywords (public, private etc., but not things like float and int) from the front of the method you're looking at (A list of which you can find here), is there anything left in front of the method?
With the Money we have at the moment, it would look like this:
Money()
Long getValue()
void makeMoney()
The constructor is the one that has no type for the return value, because it is implied in the declaration.
Question 2/3 - Get/Set methods:
I'm going to say something potentially controversial, but don't worry about these yet. Get/Set are essentially patterns for Object Oriented development, and generally good Java style, but they aren't required (Last I checked, Android development actually discourages their use when possible for optimization reasons). Moreover, not all fields in your objects will be accessible or mutable so writing them isn't mandatory.
If you declare all of your fields as public (Like the 'value' field is implied to be right now), you simple can do this:
Money myMoney = new Money(new Long(40L));
System.out.println(myMoney.value) // 40
myMoney.value = new Long(20L);
System.out.println(myMoney.value) // 20
Aside from that, the notion of get() and set() are just methods. There is nothing special about them at all. The main reason they exist is because for general Object-Oriented programming, you shouldn't have to directly modify the internal workings of an object (This is the principle of Encapsulation). Everything you should need to affect state or get something out of it should be handled by a method.
In a pithy one-liner: If you need to know the fields of an object to use it, you designed it incorrectly.
Big Picture
So what get() and set() really are is a pair of commonly written methods that happen to affect a field in an object in an extremely simple way (get() is a simple access to a field, set() is assignment to that field). It's just that other methods you write will happen to do more complicated stuff than that.

Design: Java and returning self-reference in setter methods [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
For classes that have a long list of setters that are used frequently, I found this way very useful (although I have recently read about the Builder pattern in Effective Java that is kinda the same).
Basically, all setter methods return the object itself so then you can use code like this:
myClass
.setInt(1)
.setString("test")
.setBoolean(true);
Setters simply return this in the end:
public MyClass setInt(int anInt) {
// [snip]
return this;
}
What is your opinion? What are the pros and cons? Does this have any impact on performance?
Also referred to as the named parameter idiom in c++.
#pek
Chained invocation is one of proposals for Java 7. It says that if a method return type is void, it should implicitly return this. If you're interested in this topic, there is a bunch of links and a simple example on Alex Miller's Java 7 page.
This is called a Fluent Interface, for reference.
Personally, I think it's a pretty neat idea, but a matter of taste really. I think jQuery works this way.
I wouldn't do it myself, because to me it muddies what a particular method does, and the method-chaining is of limited use to me over doing it longhand. It isn't going to send me into a quivering ball of rage and psychosis, though, which is always a good thing. :')
I wouldn't be concerned about performance; just ask Knuth.
I find this to be in poor style when used in setters. Immutable classes are usually a better fit for chaining, such as:
aWithB = myObject.withA(someA).withB(someB);
where myObject is of this class:
class MyClass {
withA(TypeA a) {
this.a.equals(a) ? this : new MyClass(this, a);
}
private MyClass(MyClass copy, TypeA a) {
this(copy);
this.a = a;
}
}
The builder pattern is also useful, since it allows the final object to be immutable while preventing the intermediate instances you would normally have to create when using this technique.
It makes sense for builders, where all you are going to do is set a load of stuff, create the real object and throw the builder away. For builders, you might as well get rid of the "set" part of the method name. Similarly, immutable types don't really need the "get".
Something thing = new SomethingBuilder()
.aProperty(wotsit)
.anotherProperty(somethingElse)
.create();
A useful trick (if you don't mind a ~2K runtime overhead per class) is to use the double brace idiom:
JFrame frame = new JFrame("My frame") {{
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocation(frameTopLeft);
add(createContents());
pack();
setVisible(true);
}};
This idea is seen a lot in c++, it allows operations to be cascaded...
for example
std::cout << "this" << "is" << "cascading"
is where the stream method << returns an instance of itself (*this).
see this: http://www.java2s.com/Tutorial/Cpp/0180__Class/Cascadingmemberfunctioncallswiththethispointer.htm
I use to be a fan of the Java (and worse C#) practice of making getters and setters (get set properties) throughout an object. This use to be what I considered object oriented, but really this leads us just to exposing the guts and implementation of the object and not really taking advantage of encapsulation. There are times you can't get away from this (OR/M comes to mind), but in general the object should be set up and then perform its function. My dream objects tend to have one or two constructors, and maybe a half dozen functions that do work.
The reason for this is that once I started developing API's there is a real need to keep things simple. You really only want to add as much complexity as is required to get the job done, and getters and setters, while simple in themselves, add complexity in heaps when added in mass. What happens when I load setters i na different order? Anythign different? Are you sure?
#Dan again, for more complex situations (immutability comes in mind) the Builder Pattern is a great solution.
Also, I agree with you mostly in getters. I believe what you are saying is to mostly follow the "Tell don't ask" paradigm and I greatly agree. But that is oriented mostly at getters.
Lastly, all of the above are for classes that have a great deal of attributes. I don't see a reason for any if you only have less than, say, 7.
I ended up doing this a lot when working with the Apache POI excel library; I ended up writing helper methods that chained so I could apply formatting, data types, internal cell data, formulas, and cell positioning.
For stuff with lots of little tiny flyweight elements that need to have finicky little tweaks applied it works pretty well.
How To Use
/**
*
* #author sanjay
*/
public class NewClass {
private int left ;
private int top;
public void set(int x,int y)
{
left=x;
top=y;
}
public NewClass UP(int x)
{
top+=x;
return this;
}
public NewClass DOWN(int x)
{
top-=x;
return this;
}
public NewClass RIGHT(int x)
{
left+=x;
return this;
}
public NewClass LEFT(int x)
{
left-=x;
return this;
}
public void Display()
{
System.out.println("TOP:"+top);
System.out.println("\nLEFT\n:"+left);
}
}
public static void main(String[] args) {
// TODO code application logic here
NewClass test = new NewClass();
test.set(0,0);
test.Display();
test.UP(20).UP(45).DOWN(12).RIGHT(32).LEFT(20);
test.Display();
I agree with #Bernard that method chaining like this muddles the purpose of the setters. Instead I would suggest that if you are always creating chains of setters like this that you create a custom Constructor for your class so instead of
MyClass
.setInt(1)
.setString("test")
.setBoolean(true)
;
You do
new MyClass(1,"test",true);
This makes it more readable and you can use this to make your class immutable if you chose to.

Categories