This question already has answers here:
Polymorphism vs Overriding vs Overloading
(21 answers)
Closed 4 years ago.
I'm struggling to know why method overloading and overriding needed in java?
I have read some articles regarding this but not able to catch why it's needed practically?
i realize after so much searching that suppose we want to load a truck with many types of vegetables(potato and tomato). our simply target is to load these in truck.now there is two way for loads these vegetables in truck.
1. one 'बोरी(sack) we full it by potato and in other we full it by tomato.
2. in one sack we can full it by tomato & potato both and in 2nd sack we can full it by also potato & tomato.
in both condition we are just load vegetables.
if vegetables are larger in the compare of truck's loading capacity then all knows that we use one more truck for loading rest of vegetables.
In whole time our target is just load these vegetables either it will come in one truck or more than one truck.
so how we can say that this is overloading.
Because on every sites of google and in every videos(example : watch video from 0:12 in given link below) everywhere overloading means to overload anything.
So my question is why overloading needed and according to my example what is difference between in overloading or loading?
https://www.youtube.com/watch?v=oPReVfof9Ws
Let me try to clear your confusion.
In general terms Overload means : too much of something but in terms of java if you are declaring same thing more then once it is called overloading. so do not get confused between term overloading and overloading in java.
Like you can declare same method(method with same name but different arguments) more then once in a particular class then it is called method overlading.
Now between loading vs overloading in a general term : if you are putting some items(x,y,z) some where that means you are increasing load on that place.
But if you are putting the items in excess that means you are overloading that place with those items.
And for why we need overloading in java, you can refer : Why is method overloading and overriding needed in java?
Related
This question already has answers here:
How do I use optional parameters in Java?
(17 answers)
Closed 1 year ago.
I need to have method that accepts let say 3 input parametars.
Calculate_Salary(int ratio, int vocationDays, int travelDays)
Many of the people do not travel, and rearly use vocation days in that case I want to call the functions in the best way (let say like in C++ only with one parametar, and other two will have default values)
There are planty of way to implement it I know (call method with zero values, overload it, implement default valuses in the body of method ). And note. it is simple with ints, it is more complex with the objects.
Calculate_Salary (ratio)
Which is the safest and fastest soulution, and is there something "new" in Java that can make this happen easy?
Thanks
As far as I know there is no solution that makes it really easy. But overloading is by far the best implementation you can do, moreover it is really easy, therefore I would go with this.
Moreover you do not need to implement a whole new function, simply call the first method with the default parameters you want.
This question already has answers here:
What does it mean to "program to an interface"?
(33 answers)
Closed 5 years ago.
I was a bit confused, when we use
List<String> lst = new LinkedList<>();
when we use
LinkedList<String> lklst = new LinkedList<>();
At the beginning, I thought they are the same, but today, I realized they are not the same. For example, if I call lst.getFirst() It will tell me there is a error. However, if i do lklst.getFirst(), it works fine. My question is when do we use lklst then? why they are different? Also, does it apply same rule for Map. THanks!
On the left hand side you're declaring the type of the variable, lst. Since lst's type is List you can only access methods of a List, even if the object lst points to is really a LinkedList. There's an inherent tradeoff between declaring a variable of a concrete type like LinkedList (access to more methods / behavior) vs. a more abstract interface (safer, better compartmentalized code).
This is a big topic, and there isn't one simple answer for when to do one vs. the other (though there's lots of advice out there about it!) - you'll need to figure out which is appropriate for your use case.
Effective Java - Item 52: Refer to objects by their interfaces is a pretty canonical citation for this issue, and as the title implies suggest preferring List rather than LinkedList.
This question already has answers here:
"Program to an interface". What does it mean? [duplicate]
(8 answers)
Closed 5 years ago.
I was reading this PowerPoint presentation when I came across this:
When you call a method through one of these references, the correct version will be called based on the actual instance of the interface being referred to. This is one of the key features of interfaces. The method to be executed is looked up dynamically at run time, allowing classes to be created later than the code which calls methods on them.
Can anyone explain me about this concept? I referred few websites and book and I am still not clear about how this concept works. From above line it is known that it calls correct version of method. How does it work and when should I cast an object to interface type.
Let's give an example using the List interface. Two of its implementations are ArrayList and LinkedList. The first one is really fast at retrieving a random element (for example the 6th using get(5) method) but is slow at adding and removing elements. The second one is the opposite. Fast at adding and removing but slow at accessing random elements.
Now lets assume that you have a class that has methods that retrieve information about a car dealership. One method retrieves a list of all available car manufacturers while the other method retrieves all the cars the dealership has. In the first case you would want to use an ArrayList because you don't expect the list of manufacturers to change that much, whereas in the second case you want a LinkedList because you expect to sell and buy lots of cars thus making many changes.
However, the one who uses those methods, doesn't really care whether he handles an ArrayList or a LinkedList. All he wants to do is use get(x) and add(Car) or remove(Car) which are all methods of the List interface. Thus, your methods should all have List as their return type and they will decide what implementation they will provide, since it doesn't matter to the one calling them.
This also gives you the advantage of being able to, in the future, change the second method for example from providing a LinkedList into an ArrayList if you decide that you need fast retrieval instead of fast adding and removing. If the method was explicitly returning LinkedList you would have to go and change all the places that it was being called into the new type. But if it was returning simply the interface then no outside change is required!
This question already has answers here:
What is the difference between an Instance and an Object?
(25 answers)
Closed 5 years ago.
I think I have read some about this topic but just let me put it clear:
I ask this to differentiate a little more "object" and "instance", although in Oracle Java tutorial I haven't seen the word "instance". I think the tutorial author avoided this expression intendedly.
https://docs.oracle.com/javase/tutorial/java/concepts/
But, inspired by some other questions here, I think there are two questions which will end this dispute:
Is every instance considered an object?
(I guess is)
and,
Is every object in Java, or in OOP, considered an instance?
(I guess no, because I think "instance" are "concrete object instantiated from a class". If an object is not constructed from instantiation, it's not an instance. However correct me if I am wrong).
In my understanding, "object" come from OOP where we see each and every concrete thing as an abstract concept, named "object". And, "instance" come from "instantiation", means "the result of a process of concretion from some class, which is a prototype.", which I have mentioned above. They are concepts with different origins but at last, in practical situations, often refer to the same thing.
If the answer to these two questions are undoubtful "YES", then they are the same. Again, correct me if I have a logical error here.
PS:
When adding tags, I see that definitions in tags of "instance" and "object" are similar.
To make it simple, an instance is a representation (unique) of an Object.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Recently I've been asked a question which is, what's the difference between Golang and Java about interface?
I know there are some 'syntactic sugar level' differences, what I am interested is anything beneath the ground, like how does Golang and Java implement interface? What's the most difference? Which one is more efficient? Why?
Could anyone post blogs link or source code about this topic? Source code is better.
Go Data Structures: Interfaces by Russ Cox
Go's interfaces—static, checked at compile time, dynamic when asked
for
Go's interfaces let you use duck typing like you would in a purely
dynamic language like Python but still have the compiler catch obvious
mistakes like passing an int where an object with a Read method was
expected, or like calling the Read method with the wrong number of
arguments.
Interfaces aren't restricted to static checking, though. You can check
dynamically whether a particular interface value has an additional
method.
Interface Values
Languages with methods typically fall into one of two camps: prepare
tables for all the method calls statically (as in C++ and Java), or do
a method lookup at each call (as in Smalltalk and its many imitators,
JavaScript and Python included) and add fancy caching to make that
call efficient. Go sits halfway between the two: it has method tables
but computes them at run time. I don't know whether Go is the first
language to use this technique, but it's certainly not a common one.
Interface values are represented as a two-word pair giving a pointer
to information about the type stored in the interface and a pointer to
the associated data. Assigning b to an interface value of type
Stringer sets both words of the interface value.
The first word in the interface value points at what I call an
interface table or itable (pronounced i-table; in the runtime
sources). The itable begins with some metadata about the types
involved and then becomes a list of function pointers. Note that the
itable corresponds to the interface type, not the dynamic type.
The second word in the interface value points at the actual data, in
this case a copy of b.
Go's dynamic type conversions mean that it isn't reasonable for the
compiler or linker to precompute all possible itables: there are too
many (interface type, concrete type) pairs, and most won't be needed.
Instead, the compiler generates a type description structure for each
concrete type like Binary or int or func(map[int]string). Among other
metadata, the type description structure contains a list of the
methods implemented by that type. Similarly, the compiler generates a
(different) type description structure for each interface type like
Stringer; it too contains a method list. The interface runtime
computes the itable by looking for each method listed in the interface
type's method table in the concrete type's method table. The runtime
caches the itable after generating it, so that this correspondence
need only be computed once.
Method Lookup Performance
Smalltalk and the many dynamic systems that have followed it perform a
method lookup every time a method gets called. For speed, many
implementations use a simple one-entry cache at each call site, often
in the instruction stream itself. In a multithreaded program, these
caches must be managed carefully, since multiple threads could be at
the same call site simultaneously. Even once the races have been
avoided, the caches would end up being a source of memory contention.
Because Go has the hint of static typing to go along with the dynamic
method lookups, it can move the lookups back from the call sites to
the point when the value is stored in the interface.
How does Go interface dispatch work?
Method dispatch on an interface variable is the same as a vtable
dispatch.
The first time a concrete type hits an interface type, it builds a
hash table entry that points to a vtable. Second and subsequent
assignments of the same type will do a much cheaper hash lookup to
find the vtable. But the method dispatch itself is always
equivalent to a vtable lookup.
Spec: Interface types
For more details see: Go: What's the meaning of interface{}?
Here, two interesting use cases of interfaces in Go:
Why are interfaces needed in Golang?
The error type is an interface type: How to compare Golang error objects
Calculate Area of 4 different shapes: Circle, Square, Rectangle and Triangle:
Explain Type Assertions in Go
Here in Go you don't need do any thing special like Java keyword implements for implementing an interface, in Go it is enough that your type just has that method with right signature.
Here is the code (try it on The Go Playground):
package main
import "fmt"
type Work struct {
Name string
}
func (t Work) String() string {
return "Stringer called."
}
func main() {
w := Work{"Hi"}
fmt.Println(w)
}
output:
Stringer called.
Spec: type Stringer, and see the source:
type Stringer interface {
String() string
}
Stringer is implemented by any value that has a String method, which
defines the “native” format for that value. The String method is used
to print values passed as an operand to any format that accepts a
string or to an unformatted printer such as Print.
Also see:
Why can't I assign a *Struct to an *Interface?
Meaning of a struct with embedded anonymous interface?
Embedded Interface
Golang: what's the point of interfaces when you have multiple inheritence