This question already has answers here:
Why is method overloading and overriding needed in java? [duplicate]
(2 answers)
Closed 5 years ago.
As if you extend the class and override the method then what will be the difference between new method and overridden method, except same name and method signature .
In the below code class A has some method parentMethod() and the same is overridden in class B by extending class A.
I want to know what is the difference between overridden method and a new method except the name and why we need to go for overridden method with classes.
class A {
void parentMethod(){
//some code
}
}
class B extends A {
void parentMethod() { //overridden method
//some overridden code
}
void childMethod() {//new method
//some new code
}
}
Overriding is used when you have two classes with very similar code. Some of the code is different so you want to have some common code and some abstract methods that can be changed from variation to variation. The variations will turn into abstract classes that extend your base class. Read more here https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html.
Override method use with example is explained below.
You can use it where you want to use the same "method name" and "signature" but need to give new code functionality.
Check the below code where,
1. class "Car" is there.
2. created default method for car as "myHorn()".
3. created new class as "Ferrari".
4. overriden the method "myHorn(), as for car i want to use new horn.
5. now for all cars you can create override the "myHorn()" method and customize code.
Class Car{
//parent class method having default horn
void myHorn(){
System.out.println("peeee..peeeee.peee");
}
}
class Ferrari extends Car{
//overridden method using same method and overriding horn
void myHorn(){
System.out.println("fuuuuuuuuuuu..fuuuuuuuuuu");
}
}
class Swift extends Car{
//Creating object of Swift class and calling method of Class "'Car"
Swift car = new Swift();
//if want to use default horn
car.myHorn();
}
}
Related
This question already has answers here:
Confusing "override a private method"
(3 answers)
Can I override a private method in Java?
(10 answers)
Java private method override
(4 answers)
Override "private" method in java
(5 answers)
Closed 4 years ago.
class Base {
private void func(){ // method overridden if public
System.out.println("In base func method");
};
public void func2() {
System.out.println("func2");
func(); // alternatively, this could be: ((Derived) this).func();
}
}
class Derived extends Base {
public void func(){
System.out.println("In Derived Class func method");
}
}
class Test {
public static void main(String [] args) {
Derived d = new Derived();
d.func2();
}
}
As written, this code will call the func() of the Base class because this method is private and there is no method overriding going on.
However, if the func() line of func2() is changed to ((Derived) this).func(), the func() of the Derived class will be called.
From what I can tell, it seems as if the Derived object is being treated like a Base object once the control enters the func2() of the Base class.
Is my understanding correct? How can my understanding be reconciled, if at all, with method overriding in the case where the func() of the Base class is instead public rather than private and runtime binding occurs? Does the call to func() in func2() first find the Base class func() and then decide to use func() in the subclass due to method overriding? Exactly what happens at runtime here?
According to what I have understood from your question, you are confused about what happens during the runtime when the method func() is called from func2() of the Base class.
When Java finds a method inside the superclass's method that is overridden in the subclass, it finds that the method is in the subclass.
So, in your case, the method func() is executed, not of the Base class but of the Derived class due to late binding. Because the Derived Object is calling the method func2(), the method func() comes back to the subclass (Derived). If, however, the call were made to the Base class, the func of the Base class would be called.
So the overall takeaway is this: Late binding is purely based off of the object calling the function. Java checks for overridden methods of the subclass during the late binding (run-time).
I have a Base class method, that I want to override in a Derived class.
The derived class method should be called whenever the method with the same name is accessed from "outside" or from the derived class. When acessing the method from inside the base class, I want the base class method to be used. Consider the following code:
public class TestBaseMethod
{
static class Basic {
public Basic()
{
Basic.this.doSomething(); // <<---- This should call Basic version
}
public void doSomething()
{
System.out.println("Doing something old");
}
}
static class Derived extends Basic {
Object ressource = new Object();
#Override
public void doSomething()
{
System.out.println("Doing something completely new");
// ressource.toString(); // <<---- explosion
}
}
public static void main(String[] args)
{
Basic d = new Derived();
System.out.println("-------------------------------");
d.doSomething(); // <<---- This should call Derived version
}
}
I want the following output:
Doing something old
-------------------------------
Doing something completely new
But it produces this output:
Doing something completely new
-------------------------------
Doing something completely new
I thought that explicitly stating the base class name in Basic.this.doSomething(); should do that trick, but apparently it does not.
Obviously, I could declare a variable of type Basic inside a Derived class instead of Deriving, but that kind of defeats the idea that the Derived class "is-a" Basic class and would force me to write oneline-redirection methods to obtain the same interface.
Here is why I want to do that:
When writing base classes, I want to use methods where I have the guarantee that inside the base class, the methods that I wrote are used, because I do not want deriving classes to interfere with base class internals. To me, it makes sense from an encapsulation standpoint, but maybe I am wrong?
The Basic#doSomething() method can be called from the Basic() constructor.
If the Derived#doSomething() method uses ressources from Derived, then those ressources will only be available after Derived construction.
However: Derived construction finishes AFTER the superclass construction, which means that when Derived is constructed, the Derived#doSomething() is called in the Basic() constructor and it will access uninitialized data.
Is there a way around this?
Calling veritable methods from a constructor is a bad practice, more could be found here: On invoking overridable method from constructors
As for enforcing to call the base class method - it's impossible.
Make an inner method in Basic for doSomething and call that directly:
static class Basic {
public Basic()
{
doSomethingImpl();
}
public void doSomething()
{
doSomethingImpl();
}
private void doSomethingImpl()
{
System.out.println("Doing something old");
}
}
What you want to do is bad, from a design point of view. A good design would be to declare two separate methods, one overridable and the other not (either final or private).
This question already has answers here:
Calling super super class method
(12 answers)
Closed 8 years ago.
Let say I have three classes:
class A
{
public void method()
{ /* Code specific to A */ }
}
class B extends A
{
#Override
public void method()
{
/*Code specific to B*/
super.method();
}
}
class C extends B
{
#Override
public void method()
{ /* I want to use the code specific to A without using B */ }
}
The goal in this case is to use the code from A without using the code from B. I thought there was a way to do it by calling the super method, but this brings in the code from B as well.
Is there a way to do this?
The short answer is no. What you're seeing is that your design is flawed. It indicates that you need too move the code in class A out into a helper class. B and C would then use it via composition. You could try using partials to get the behavior you want. See this link for more details. Partial function application in Java 8
You could instantiate an object of class A in C and call the method method
class C extends B
{
#Override
public void method()
{ /* I want to use the code specific to A without using B */
A test = new A();
test.method();
}
}
Not sure if this is what you meant. Also asumed you forget the method name method in class A.
No there is no way to do it. You can simply create another method in class B that executes the code of A's method, and call that method in subclass C.
This question already has answers here:
Hidden fields though inheritance
(3 answers)
Closed 9 years ago.
Guys,
My question is very simple. Look at the following code:
public class Test {
public static void main(String[] args){
SubTest st = new SubTest();
st.sayName();
}
}
class BaseTest{
String name= "BaseTest";
void sayName(){
System.out.println(getClass());
System.out.println(this.name);
}
}
class SubTest extends BaseTest{
String name= "SubTest";
}
Output:
xxx.xxx.SubTest
BaseTest
I know the methods will be inherited or overridden and the fields will be shadowed in the inheritance. So it is supposed that the value of subclass is printed, not that of baseclass. However, there must be something I dropped. Hope someone can tell me.
Thanks.
Instance variables are not subject to polymorphism as methods are. So, yes, SubTest inherits the sayName() method from BaseTest, but the method still refers to BaseTest's name variable. Note that the SubTest class now has two name instance variables.
To print "SubTest", you could override sayName():
#Override
void sayName(){
System.out.println(getClass());
System.out.println(this.name);
}
Here, this.name would refer to SubTest's name variable.
Your method is defined in the BaseTest. It is unaware of who inherits it. it does not know that there is a SubTest class. So when you print the value, you print the value of name from the BaseTest class.
If you want to print the value of name in SubTest then you must override the method in SubTest. Since you have not overriden the method, all your calls are automatically to the inherited sayName() which, as I said, prints the name from BaseTest
Place this code in your SubTest class:
#Override
void sayName(){
super.sayName(); // calls sayName() of the super class
System.out.println(this.name); // prints value of name in the SubTest class
}
This question already has answers here:
Abstract methods in Java
(3 answers)
Closed 8 years ago.
I am slightly confused with the keyword abstract here. My compiler is telling me that I am not allowed to have a body for a method that's abstract. However my assignment says:
The abstract method orderDescription() returns a String giving details about a particular order.
abstract String orderDescription()
{
return null;
}
However my code returns an error, as I mentioned above. So my question is what should I do for this problem?
Up to now I've just removed the keyword abstract and it works fine.
abstract String orderDescription()
{
return null;
}
should be
abstract String orderDescription();
As error says, your abstract method declaration shouldn't contain any body.
Above syntax mandates the implementation (which ever class extends the abstract class and provides implementation) to return a String.
You can't instantiate abstract class, so some class need to extend abstract class and provide implementation for this abstract method.
Example:
class MyabsClass
{
abstract String orderDescription();
}
class MyImplementation extends MyabsClass
{
public String orderDescription()
{
return "This is description";
}
}
class MyClient
{
public static void main(String[] args)
{
MyImplementation imple = new MyImplementation();
imple.orderDescription();
}
}
When you define an abstract method, you are telling the compiler that any subclasses must provide an implementation (or also declare themselves abstract).
You implement the abstract method in a subclass.
Remember, you cannot create instances of abstract classes themselves. The entire point of an abstract method is to tell the compiler that you want subclasses to provide the functionality.
Essentially, an abstract function shouldn't contain any details, it is a placeholder function for inherited functions. As Nambari stated, you should only include the definition.
This is used for when you want a family of classes to all contain a common function, which you wish each child class to define.
Abstract methods generally shouldn't contain any "real" code, abstract methods are to be overidden by non-abstract classes containing the method.
Abstract method should not have any method body. It allows only method declaration.
Also, adding to Nambari's example, what you can do is
class MyabsClass
{
abstract String orderDescription();
}
class MyClient
{
public static void main(String[] args)
{
MyabsClass mac = new MyabsClass(){
public String orderDescription()
{
return "This is description";
}
};
mac.orderDescription();
}
}
That is, through anonymous class.