private method of superclass executes on subclass reference - java

Given the following code:
SuperClass :
package poc.poc;
public class SuperClass {
private void method() {
System.out.println("SuperClass!");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SuperClass s = new SubClass();
s.method();
}
}
SubClass :
package poc.poc;
public class SubClass extends SuperClass {
public void method() {
System.out.println("Subclass!");
}
}
When I run the main method of SuperClass , I would expect to get an exception of some sort, but actually the code in the SuperClass is run, rather than the code in the SubClass, and therefore running an instance method of the superclass type on a subclass instance.
Why does this happen?
EDIT: Doesn't this violate encapsulation?
P.S. When changing to protected rather than private modifier, polymorphism starts to kick in and we're back to something I would call "expected behavior"

There is no way to override a private method. Instead, the subclass is hiding it. That means that when the subclass is used polymorphically, the method is not considered one of the parent's existing methods. It's like a whole new method that's not available through polymorphism.
The private method is not part of the parent's class contract. Polymorphism only applies to methods that are part of the parent's contract. If it wasn't like that, you could cause a class to act differently than its contract, by changing implementation where the author wanted it to be private. If the author wanted you to do that, they would have used protected instead. In effect, a private method is like final.
In this particular main method, because it is defined in the actual parent's class, it is able to see a private method and therefore able to call it. If your main method has been in any other class and tried to call it, it would have failed.

A private method cannot be overrided, that alone explains what you see here. You are able to call the method in your main because the main is in the same class, otherwise it would not be possible.
You correctly analyzed what happens when changing private to protected : the method is now overridable and the "nearest" definition of it is executed when calling it on a subclass instance.

Related

Override "private" method in java

There something ambiguous about this idea and I need some clarifications.
My problem is when using this code:
public class B {
private void don() {
System.out.println("hoho private");
}
public static void main(String[] args) {
B t = new A();
t.don();
}
}
class A extends B {
public void don() {
System.out.println("hoho public");
}
}
The output is hoho private.
Is this because the main function is in the same class as the method don, or because of overriding?
I have read this idea in a book, and when I put the main function in another class I get a compiler error.
You cannot override a private method. It isn't visible if you cast A to B. You can override a protected method, but that isn't what you're doing here (and yes, here if you move your main to A then you would get the other method. I would recommend the #Override annotation when you intend to override,
class A extends B {
#Override
public void don() { // <-- will not compile if don is private in B.
System.out.println("hoho public");
}
}
In this case why didn't compiler provide an error for using t.don() which is private?
The Java Tutorials: Predefined Annotation Types says (in part)
While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with #Override fails to correctly override a method in one of its superclasses, the compiler generates an error.
is this because the main function is in the same class as the method "don"
No, it's because A's don() is unrelated to B's don() method, in spite of having the same name and argument list. private methods are hidden inside their class. They cannot be invoked directly by outside callers, such as main method in your case, because they are encapsulated inside the class. They do not participate in method overrides.
No, a private method cannot be overridden since it is not visible from any other class. You have declared a new method for your subclass that has no relation to the superclass method. One way to look at it is to ask yourself whether it would be legal to write super.func() in the Derived class.
You can't override a private method, but you can introduce one in a derived class without a problem. The derive class can not access the private method on the ancestor.
Since t is a on object of type B, calling don() method will invoque the method defined at B. It doesn't even know that there is a method named also don() at class A
private members aren't visible to any other classes, even children
You can't override a private method, but then again, you can't call it either. You can create an identical method with the same name in the child however.
public class A
{
private int calculate() {return 1;}
public void visibleMethod()
{
System.out.println(calculate());
};
}
public class B extends A
{
private int calculate() {return 2;}
public void visibleMethod()
{
System.out.println(calculate());
};
}
If you call A.visibleMethod() it prints out 1.
If you call B.visibleMethod() it prints 2.
If you don't implement the private calculate() method in B, it won't compile because the public method that calls it can't see the private method in A.

Invoke a method of a class which is implemented in her supperclass

I have a class java ProductManager which extends another class with the same name,
located in another project with another package("com.services") .
I have to invoke a method deleteProduct(Long productId) located in the super-class.
try{
Object service = CONTEXT.getBean("ProductManager");
Method method = service.getClass().getDeclaredMethod("deleteProduct", Long.class);
method.invoke(service, productId);
} catch(Exception e){
log.info(e.getMessage());
}
I couldn't delete the product:
I get this info:
com.franceFactory.services.ProductManager.deleteProduct(java.lang.Long)
the product isn't deleted :(
The various getDeclaredMethod() and getDeclaredMethods() only return methods declared on the current class instance. From the javadoc:
This includes public, protected, default (package) access, and private methods, but excludes inherited methods.
The important part here is "but excludes inherited methods". This is why you are getting an exception with your code as it currently stands, it is not returning the deleteProduct() method from the parent class.
Instead if you wanted to continue using reflection you would need to use the getMethod method as this returns all public methods, "including those declared by the class or interface and those inherited from superclasses and superinterfaces."
If you have to use reflection then don't use getDeclaredMethod() because (as its name suggest) it can return only methods declared in current class, while you claim you want to invoke method declared in other class (to be precise declared in super class).
To get public method (including also inherited ones) use getMethod().
If your are overriding that method, just use the reserved word super (from the Oracle documents):
public class Superclass {
public void printMethod() {
System.out.println("Printed in Superclass.");
}
}
public class Subclass extends Superclass {
// overrides printMethod in Superclass
public void printMethod() {
super.printMethod(); // This calls to the method defined in the superclass
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}
This code will write:
Printed in Superclass.
Printed in Subclass
In other case (you are not overriding it, just using it), just write this.methodName(...). All methods inherited are directly available.
Disclaimer: I am not sure I totally understand your question. I will still try to answer what I think I understand.
The Product in package com.franceFactory.services (Lets call it A)
extends The Product class in package com.services (Lets call it B)
So A extends B.
B has method deleteProduct(java.lang.Long)
A overrides the method deleteProduct(java.lang.Long)
You have instance of Class A. So by OOPS concept method deleteProduct of object A is going to get called.
There is no way you can call the super method from outside unless you have the instance of class B.
EDIT
OPs Clarification yes, it's public, but it isn't overridden in my class
The method in super is getting called here. The product is not getting deleted for reason on what is written on the method.

Inheriting static methods in Java?

So I know that in Java when you have a static method you are supposed to call it with the format ClassName.method() rather than use the same structure as you would for instance methods, namely:
ClassName myObject = new ClassName();
myObject.method();
However, if you were to do it this way it would still be valid code and would work. Let's say I decide to do this where the method in question is static, and have the following setup:
public SuperClass {
public static int foo(int x) {
return x;
}
}
public SubClass extends SuperClass {
public static int foo(int x) { // Overriding foo() in SuperClass
return x + 1;
}
}
public MyDriver {
public static void main(String[] args) {
SuperClass myObject = new SubClass(); // Upcasting.
System.out.println(myObject.foo(5)); // This should polymorphically print 6
}
}
What prints out on the screen, however, is 5 rather than 6. Why?
Static methods apply only to the class they are defined in, and they cannot be overridden.
When you call myObject.foo(5), you are calling SuperClass.foo(5) in reality, because you declared myObject as a SuperClass, regardless of whether you instantiated it as one.
The proper way to call a static method is to call it directly from the class it is declared in, so if you wanted to call SubClass.foo(), you must call it from an explicitly declared SubClass instance (meaning no upcasting), or you need to call SubClass.foo() like so.
The simple answer is that calling static methods from instances evaluates to calling those same methods from the declared type with no instance rather than the instance type.
I am not certain of this, but I would not be surprised if when the code is compiled into byte-code, that the instance static method call would actually be compiled into a direct call to the declared type.
Edit: An upvote brought my attention back to this and I cleaned up the explanation to make it more clear and fix some negligible grammatical mistakes on my part. I hope this helps future readers.
Using instances of a class to call that class's static methods is something you should avoid, since it can cause confusion. If you need to call any method polymorphically, make it an instance method. You cannot polymorphically call a static method. The reason the SuperClass invocation is called is because that is the apparent class of myObject at compile-time. This effect can also be seen in the following scenario:
public void doSomething(SuperClass param) {
System.out.println("SuperClass");
}
public void doSomething(SubClass param) {
System.out.println("SubClass");
}
public void test() {
SuperClass myObject = new SubClass();
doSomething(myObject);
}
If test() is called, SuperClass will be printed.
Static methods don't depends on the instance, they belong to the class and only to the class, in fact if you have a static method you'll always access to one unique instance always.
myObject.foo(5)
is only a shortcut, what you really are doing is
SuperClass.foo(5)
Static methods are treated as global by the JVM, they are not bound to an object instance at all. By the way, you can only overload static methods, but you can not override. So check for "Oracle Documentation for Overriding and Hiding Documents".
Defining a Method with the Same Signature as a Superclass's Method:
-----------------------------------------Superclass Instance MethodSuperclass Static Method
Subclass Instance Method Overrides Generates a compile-time error
Subclass Static Method Generates a compile-time error Hides

why should we widen the accessibility of overridden methods?

why should we widen the accessibility of overridden methods ? If the super class has a protected method and subclass has same method with public. Why should happen?
It's a different method! Subclasses don't inherit private methods! So you're not "overriding" at all. You are simply DEFINING a method with the same name as the private method in the superclass.
class A
{
private void myMethod() { }
}
class B extends A
{
public void myMethod() { } // a completely different method. Has nothing to do with the above method. It is not an override.
}
Because in an object hierarchy, JVM will always run the Overriden method. If your overriden method is not accessible, then it is useless.
public class A{
void A(){}
}
public class B extends A{
private void A(){} //this makes no sence and its impossible
PSV main(String ..){
A a = new B();
a.A(); //error as JVM cannot call overriden method which is private.
}
}
Methods declared as private or static can not be overridden!
Annotation #Override indicates that a method declaration is intended to override a method declaration in a superclass. If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message.
Use it every time you override a method for two benefits. This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warned that you method does not actually override as you think it does. Secondly, it makes your code easier to understand because it is more obvious when methods are overwritten.
And in Java 1.6 you can use it to mark when a method implements an interface for the same benefits.

Confused with Java Overriding the access level [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why can't you reduce the visibility of a method in a java subclass?
How come I can override a private method in superclass with a public when in a subclass, but I cannot override a public method in the superclass into private method in subclass?
Why?
Thank you in advance.
Overriding a method can't ever reduce the visibility. Allowing that would violate the Liskov Substitution Principle, which states (simplified) that all objects of a derived class B must have the same properties as the base class A. In this case one such "property" would be a public method foo which would be "lost" if B had that same method, but made it protected.
Also, since private methods are not inherited (try calling it from a derived class!) they can't ever be overriden. You can have a public method with the same name as a private one in the base class, but that's not overriding, it's simply a new method with the same name, but not other relation. Calls to the private method in the base class will not call the public method in the superclass, even when executed on objects of the superclass!
In other words: private methods never use runtime polymorphism.
See this sample:
public static class Base {
public void callBoth() {
foo();
bar();
}
private void foo() {
System.out.println("Base.foo");
}
protected void bar() {
System.out.println("Base.bar");
}
}
public static class Sub extends Base {
public void foo() {
System.out.println("Sub.foo");
}
public void bar() {
System.out.println("Sub.bar");
}
}
When executing new Sub().callBoth() the output will be this:
Base.foo
Sub.bar
Because it doesn't break the class contract to make a method more available. If Kitten subclasses Animal, and Animal has a public method feed(), then Kitten must also have a public method feed(), as it must be possible to treat any instance of Kitten like an instance of Animal. Redefining the access level to private would break that.
If the public method became private, then it would not be possible to up cast the instance into its parent class (because one of the methods would be unavailable).
If the private method became public, then it would be possible to up case the instance into its parent class (because then you would just have no way to grab the private / publicly overriden method).
The access level can't be more restrictive than the overridden method.
private-->[default]-->protected-->public
By overriding you're saying that your subclass can be called with the same api but may function differently. Making something public increases the access level - so you're not removing guaranteed functionality.
By making a public method private (if you could actually do this) you'd be removing functionality, so breaking the "contract". It also doesn't make sense in that the method could still be called publicly, it's just that the public call would access the public method in the superclass, which would be counterintuitive.

Categories