#Override in java - java

Let's say I got the following, I would even call it pseudo-code
public class someClass {
public someClass{
example("Hello Stackoverflow");
}
#Override
public void example(){
System.out.println("Hello World");
}
public void example(String Hello){
System.out.println(Hello);
}
}
In this code the method public void example(String Hello) would be called instead of the public void example() method. How is the compiler working in this case ? The compiler has to decide which method to call in this case, because they got the same name. Is there something like an order e.g. first try #Override method, if that's not working go for the normal one. Or how does that work ?

No, what you've shown isn't overriding at all - it's overloading. (The use of the #Override annotation is obviously to do with overriding, but it's incorrect used here - there's no superclass method to override.)
Overriding is when a method signature is declared in a superclass, and then overridden in a subclass (with the same signature). The method implementation is chosen at execution time based on the execution-time type of the object you call it on.
Overloading is when more than one method is present with the same name, but different signatures. When invoking the method, the correct signature is picked at compile time based on the compile-time types of the arguments to the method.
For example:
public void foo(int x) {}
public void foo(String y) {}
public void foo(Object o) {}
public void foo() {}
foo(50); // Calls the first method
foo("hello"); // Calls the second method
// Calls the third method, because the compile-time type of the argument is
// Object, even though it's actually a reference to a string at execution time
foo((Object) "hello");
foo(); // Calls the fourth method

The #Override annotation tells the compiler: "Please fail to compile me unless I'm overriding an existing method defined in a parent class or an interface I implement."
However, you are doing method overloading - i.e. methods with the same name but different arguments.
Consequently, your code won't compile because your example() method doesn't override a method in a parent class or interface. Instead, it overloads another method in the same class. There is no annotation for that.
An example of a valid override would be adding a toString() method to your class, which would override the method declared in the Object class:
public class someClass {
public someClass{
example("Hello Stackoverflow");
}
public void example(){
System.out.println("Hello World");
}
public void example(String Hello){
System.out.println(Hello);
}
#Override
public String toString() {
return "Hello, World!";
}
}

Because you are calling a function with a parameter
example("Hello Stackoverflow");
that is function overloading study about overloading here
This has nothing at all to do with the #Override annotation.

This has nothing at all to do with the #Override annotation.
You can overload methods: having more than one method with the same name but different types and number of parameters.
The compiler will choose the method with the signature that matches best (the exact rules are a bit complicated since Java5, what with varargs and auto-boxing).
In your case, you call a method with a String parameter.
A method without parameters does not apply, will not be considered.

It's not an #Override since you do not override a parent method and code will not compile.
This is overload.
Here, you have 2 distinct methods. One take a parameter and the other one not.
So it simple:
when you call method with a parameter, it's the example(String hello) which will be called.
when you call method without a parameter, it's the example() method which will be called.
This is not an override.

Related

How is the .toString() overloaded in the Arrays class

I came across the concept where a method cannot be overridden and overloaded at the same time. But when I used Arrays.toString(),
Correct me if I'm wrong, but the toString() method has been overridden and overloaded at the same time. How is that possible?
You are overriding when you have the exact same method signature in a subclass. You are overloading when you have two equal named methods with different type or number of parameters. You can override a method and then overload it but you can write a method and it can happend that when you overload it you end up overriding a super class method. One thing doesn't exclude the other.
Let's have a Super class like this:
public class Super {
public void testMethod() {}
// Overload
public void testMethod(String param) {}
}
And then extend it with a sub class like this:
public class Sub extends Super {
// Override only
#Override
public void testMethod() {}
// Overload only
public void testMethod(int param) {}
// Overload and Override
#Override
public void testMethod(String param) {}
}
As you can see, you can have only overload, only override or both in multiple ways. As said, one thing doesn't exclude the other.

How to call a base class method

How to call a base class method. In the method "test" of the "invoke" class, I'm trying to upcast to the base type to call exactly its method, but for some reason I have an equal call to the derived method
class BaseClass {
protected void print(){
System.out.println("This is method print from BaseClass");
}
}
class DerivedClass extends BaseClass{
#Override
protected void print() {
System.out.println("This is method print from DerivedClass");
}
}
public class invokeDrawing{
public void test() {
DerivedClass derived = new DerivedClass();
derived.print();
System.out.println("****************");
BaseClass derivedTest = (BaseClass)derived;
derivedTest.print();
}
}
You could add a method on it which would call the superclass method specifically, like this:
public void superPrint() {
super.print();
}
And then call it from your derived class:
derived.superPrint();
Java polymorphism works differently than you expect. When a method of an object is called, the 'most specific' method is invoked, unless specified otherwise. This makes sense, because you always want your object to behave the way the implementation intends, and not the way the base class intends (because the base class does not know the specific class - In other words, you have more context in the derived class, and therefore that behavior is more applicable).
In your example, the object is still of type DerivedClass despite you 'casting' it to BaseClass. The casting only shrouds the fact that you actually have a DerivedClass-Object, but the behavior still comes from the method overriden in DerivedClass.
If you want to invoke a super-method from a derived class, you can use the super keyword:
public String toString() {
return "123 " + super.toString();
}
There are hacks to work around this, if you really, really need it, but usually you don't.

Is it overloading or overriding?

I have a code and I am not able to get why the output will be "Radial Tire with long".Can somebody help me to understand this code?
class Tyre {
public void front() throws RuntimeException {
System.out.println("Tire");
}
public void front(long a) {
System.out.println("Radial Tire with long");
}
}
class TestSolution extends Tyre {
public void front() {
System.out.println("Radial Tire");
}
public void front(int a) throws RuntimeException {
System.out.println("Radial Tire with int");
}
public static void main(String... args) {
Tyre t = new TestSolution();
int a = 10;
t.front(a);
}
}
front is not overridden in TestSolution, it is overloaded.
You can regard an overloaded function as a completely different function, like one with a different name.
So t.front(a) will call the one in Tyre, with an a implicitly converted to long.
So if we go with definitions
Overloading means methods with same name but with different number or order of parameters.
Overriding means method with same name with same number of parameters along with rules mentioned here
So in your case front method is overloaded in both the classes Tyre and TestSolution
method front() from Tyre class is overridden in class TestSolution.
no overriding in case of method front(long a) and front(int a).
There's no overriding taking place in your main.
t's static (compile-time) type is Tyre, so, since method overload resolution is determined by the compile-time type of the instance, the only front methods available for the compiler to choose from are those declared in the base class Tyre :
public void front()
public void front(long a)
Only the latter (public void front(long a)) matches the arguments of the call t.front(a), and that method is not overridden by the sub-class. Therefore Radial Tire with long is displayed.
Calling ((TestSolution)t).front(a); would invoke the sub-class's method - public void front(int a).
General rule: if I have a variable of one class I can access only methods and components defined in that class.
The only particular case is:
you have a component or method both in the super class and in the subclass (overriding)
you have a variable of the super class and an object of the subclass (your case)
In these cases you can follow the following rule:
for the components the type of the variable decides which to use
for the methods the type of the object does (late binding)
In your case as stated before the method is not overridden so you can't apply the last rule.
Lets understand the difference between overloading and overriding
Overloading:
The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists
Overriding:
An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.
Tyre declared front() method with long as parameter.
TyreSolution declared front() method with int as parameter.
Since the method signature is different, TyreSolution overloads Tyre's front() method
If you change signature of front() in TyreSolution to accept long value as input parameter instead of int, then TyreSolution overrides Tyre's front() method.
e.g. TestSolution class definition of front() method
public void front(long a) throws RuntimeException {
System.out.println("Radial Tire with long in TestSolution");
}
output:
Radial Tire with long in TestSolution

How to call parent class method which has another parent class in Java?

So I have class A extends class B, class B extends JInternalFrame, B has a method myMethod (in my case myMethod converts an order system to decimal numbers). Now I want to use myMethod from class B in a method in class A, but when I try to call super.myMethod() it says myMethod() is not found, and when I took a look at all the methods that show up after typing "super.", the methods are all JTable methods (if I control click any method from the drop down I go to JTable.java).
I have tried creating a B in class A then use B.myMethod(), this works but is there a way to call myMethod in class A without making a B?
public class B extends JInternalFram{
constructor(){
}
public myMethod(){
//does conversions here
}
}
public class A extends B{
constructor(){
}
public anotherMethod(){
//needs to use b.myMethod();
}
}
Thanks
Mmmmm Im not sure but arent you missing the return Type?
Try changing:
public myMethod(){//does conversions here}
With:
public void myMethod(){//does conversions here}
Remember:
In general, a method has the following syntax:
modifier returnValueType methodName(list of parameters) {
// Method body;
}
Modifiers: The modifier, which is optional, tells the compiler how to call the method. This defines the access type of the method.
Return Type: A method may return a value. The returnValueType is the data type of the value the method returns. Some methods perform the desired operations without returning a value. In this case, the returnValueType is the keyword void.
Method Name: This is the actual name of the method. The method name and the parameter list together constitute the method signature.
Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.
Method Body: The method body contains a collection of statements that define what the method does.
Hope this helps -
public class B extends JInternalFram{
B(){
}
public void myMethod(){
//does conversions here
System.out.println("Inside myMethod of B");
}
}
public class A extends B{
A(){
}
public void anotherMethod(){
//needs to use b.myMethod();
myMethod();
}
}
First of all, use void as a return type in both Methods, otherwise JVM thinks it is a constructor. Back to the main problem, why don't you use super.myMethod()?
Bye,
J

What does it mean to #override the method of a super class?

Let's say I have a method called mymethod()
and this method overrides the method of the super class method.
What does it mean to override a method?
Does that mean mymethod() ignores everything that is in the method of the superclass, or does that means mymethod() also includes everything in the superclass method?
When overriding a method, can I only override the methods of the same name, or I can override methods of any name?
thanks.
An example:
public class Base {
public void saySomething() {
System.out.println("Hi, I'm a base class");
}
}
public class Child extends Base {
#Override
public void saySomething() {
System.out.println("Hi, I'm a child class");
}
}
Now assume we have a main function somewhere...
public static void main(String [] args) {
Base obj = new Child();
obj.saySomething();
}
When this runs, it will call Child's version of saySomething, because you overrode the parent's version by giving a new version of the function in Child.
The #Override annotation allows other developers (and you, when you forget) to know that this method overrides something in a base class/interface, and it also allows the compiler to yell at you if you're not actually overriding anything in a base class. For example, if you got the number of arguments wrong for a function, the compiler will give you an error saying your #Override is incorrect.
For example:
public class Child extends Base {
#Override
public void saySomething(int x) {
System.out.println("I'm a child and x is: " + x);
}
}
The compiler will yell at you because this version of saySomething takes an argument, but the parent's version doesn't have an argument, so you're #Override-ing something that's not in the parent.
On super
The Child version of saySomething will not invoke the Base version, you have to do it yourself with super.method().
For example:
public class Child extends Base {
#Override
public void saySomething() {
super.saySomething();
System.out.println("I'm also a child");
}
}
If you ran the main and used this Child class, it would print out I'm a base and I'm also a child.
Overriding means that when you call a method on your object, your object's method is called instead of the super class. The #Override annotation is something you use to make sure that you are overriding the correct method of the superclass. If you annotate a method that does not exist in the superclass, the Java compiler will give you an error. This way you can be sure that you are overriding the correct methods. This is especially useful in cases like this:
public class MyClass {
...
public boolean equals(MyClass myClass) {
...
}
}
There is a logic-bug in the code above. You haven't actually overridden the Object class's equals method. If you add the #Override annotation:
public class MyClass {
...
#Override
public boolean equals(MyClass myClass) {
...
}
}
The Java compiler will now complain because there is no corresponding method in the parent class. You'll then know that the correct solution is:
public class MyClass {
...
#Override
public boolean equals(Object o) {
...
}
}
To call the parent class's method, you can call super.overriddenMethod() where overriddenMethod is the name of the method you have overridden. So if you want to do something in addition to what the parent class already does, you can do something like this:
public class MyClass {
...
#Override
public void overriddenMethod() {
super.overriddenMethod();
/* whatever additional stuff you want to do */
}
}
If an inheriting class has on override method of the same name as the parent class it will be called instead of the one in the parent class. This only works if the names are the same, and of course if the signature of the method matches your call to the method.
What does it mean to override a method?
It means you replace the super class definition of the method with your own definition.
does that mean mymethod() ignores everything that is in the method of the super class?
or does that means mymethod() also includes everything in the superclass method?
You can choose whether to include the super class definition within your definition. To include it, you need to call super.mymethod() within mymethod().
and when overriding a method, can I only override the methods of the same name, or I can override methods of any name?
To override a method, you must supply a method in the sub class with the same signature (which means the same name, parameters and return type).
As a side note, the #Override annotation in your question does not actually cause your method to override another method. It causes a compile-time error if a method annotated with it does not have a signature matching a public or protected method of a super class (or interface as of 1.6).
I once had a student come to ask me why his code wasn't working. He had spent several days wondering why he could put something into a collection but was not able to find it. His code was something like:
public int hashcode()
instead of:
public int hashCode()
So the hashCode method never got called.
Adding #Overrides to a method makes it clear that you are overriding the method AND make sure that you really are overriding a method.
When you override a method of the super class, calling that method on your object calls its method instead of that of the super class.
You can call the super class's method (despite having overridden it) using super.methodName(). A common reason for this is when the overridden method would otherwise reimplement the super class method and add additional code specific to the extending class (public void methodName() { super.methodName(); /* more code */ }).
#Override annotation allows you to cause warning at compile time if the method isn't actually overriding anything. It isn't necessary, but these warning are a hit to you that you might have got the signature wrong in the extending class, forgot to implement the method at all in the super class, or some other silly mistake.

Categories