Confused with Java Overriding the access level [duplicate] - java

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.

Related

private method of superclass executes on subclass reference

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.

what is the implicit declaration of interface methods in Java 8?

I was reading my old SCJP 6 book(author Kathy Sierra,Bert Bates) mentioned
All the interface methods are implicitly public and abstract by default
interface methods must not be static
For example, if we declare
interface Car
{
void bounce(); //no need of public abstract
void setBounceFactor(int b); //no need of public abstract
}
What the compiler sees
interface Car
{
public abstract void bounce();
public abstract void setBounceFactor(int b);
}
But from Java 8, interfaces can now define static methods. see this article everything-about-java-8
My question, what is the implicit declaration of interface methods in Java 8? Only public or nothing?
The rules for implicit modifiers do not change. Implicit modifiers are used when no other modifiers are specified. abstract is implied when neither static nor default has been specified. And all methods are always public whether implicit or explicit. Note that interface fields were always implicitly public static. This doesn’t change too.
But for the final words we should wait for the completion of Java 8.
Afaik it is something you can add and is added without changes to implementing classes.
For example. The List class will have a sort() method added. A sub class could have this method already but if every class needed this method it would break a lot of code and make having a default a bit useless.
I believe it is expected that the default method will be simple and call a static method or helper class to leave the interface uncluttered.
in short, default methods are public but not abstract.
btw interfaces have a method for static field initialisation.
what is the implicit declaration of interface methods in Java 8? Only
public or nothing?
Answer is: It is still public. private or protected are restricted. Look at following two examples
public interface A {
static void foo() {// Its ok. public will implicitly call.
System.out.println("A.foo");
}
private static void foo2() {// Compile time error
System.out.println("A.foo2");
}
}

Using this and super in Java

I have the following code snippet that attempts to use this and super.
class SuperClass
{
public final int x=10;
public final String s="super";
public String notOverridden()
{
return "Inside super";
}
public String overrriden()
{
return "Inside super";
}
}
final class SubClass extends SuperClass
{
private final int y=15;
private final String s="sub"; //Shadowed member.
#Override
public String overrriden()
{
return "Inside sub";
}
public void test()
{
System.out.println(super.notOverridden());
System.out.println(this.notOverridden());
System.out.println(this.overrriden());
System.out.println(super.overrriden());
System.out.println(this.s);
System.out.println(super.s);
System.out.println(this.x);
System.out.println(super.x);
System.out.println(this.y);
}
}
public final class Test
{
public static void main(String[] args)
{
SubClass subClass=new SubClass();
subClass.test();
}
}
In this simplest of Java code, the statements that redirect the output to the console inside the method test() within the class SubClass display the following output.
Inside super
Inside super
Inside sub
Inside super
sub
super
10
10
15
So, it appears that there is no difference between this and super, when they are used to access methods which are not overridden in its subclass(es) and in case of variables, when they are not shadowed in its subclass(es).
Both of them tend to point to super class members. There is however, an obvious difference, if such is not a case.
Are they same, when methods are not overridden or variables are not shadowed in respective subclasses?
So, it appears that there is no difference between this and super,
when they are used to access methods which are not overridden in
its subclass(es) and in case of variables, when they are not
shadowed in its subclass(es).
There is a difference. If you override methods in third class, and call test from it, you will see, that super still calls implementations of SuperClass. And this will call new implementations (overridden).
Addition:
this.method() usage implies the method belongs to instance of the object. So the last implementation will be used (with exception of private methods).
super.method() usage implies method of the instance, but implemented before the current class (super, or super.super etc).
Yes, they are the same. notOverridden methods and not shadowed variables are inherited by subclass.
To better understand this, knowing how object is located in memory is helpful. For example in the figure below. Assume it's an object of a subclass. The blue area is what it inherits from its parent, and the yellow area is what is defined by itself. The method has the similar design except that it uses a Vtable.
Child object has the same memory layout as parent objects, except that it needs more space to place the newly added fields. The benefit of this layout is that a pointer of parent type pointing at a subclass object still sees the parent object at the beginning.

Use of 'super' keyword when accessing non-overridden superclass methods

I'm trying to get the hang of inheritance in Java and have learnt that when overriding methods (and hiding fields) in sub classes, they can still be accessed from the super class by using the 'super' keyword.
What I want to know is, should the 'super' keyword be used for non-overridden methods?
Is there any difference (for non-overridden methods / non-hidden fields)?
I've put together an example below.
public class Vehicle {
private int tyreCost;
public Vehicle(int tyreCost) {
this.tyreCost = tyreCost;
}
public int getTyreCost() {
return tyreCost;
}
}
and
public class Car extends Vehicle {
private int wheelCount;
public Vehicle(int tyreCost, int wheelCount) {
super(tyreCost);
this.wheelCount = wheelCount;
}
public int getTotalTyreReplacementCost() {
return getTyreCost() * wheelCount;
}
}
Specifically, given that getTyreCost() hasn't been overridden, should getTotalTyreReplacementCost() use getTyreCost(), or super.getTyreCost() ?
I'm wondering whether super should be used in all instances where fields or methods of the superclass are accessed (to show in the code that you are accessing the superclass), or only in the overridden/hidden ones (so they stand out).
Don't use the super keyword to refer to other methods which aren't overridden. It makes it confusing for other developers trying to extend your classes.
Let's look at some code which does use the super keyword in this way. Here we have 2 classes: Dog and CleverDog:
/* file Dog.java */
public static class Dog extends Animal {
private String name;
public Dog(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
/* file CleverDog.java */
public class CleverDog extends Dog {
public CleverDog(String name) {
super(name);
}
public void rollover() {
System.out.println(super.getName()+" rolls over!");
}
public void speak() {
System.out.println(super.getName() + " speaks!");
}
}
Now, imagine you are a new developer on the project, and you need some specific behavior for a clever dog who is on TV: that dog has to do all its tricks, but should go by its fictitious TV name. To accomplish this, you override the getName(...) method...
/* file DogOnTv.java */
public class DogOnTv extends CleverDog {
String fictionalName;
public DogOnTv(String realName, String fictionalName) {
super(realName);
fictionalName = fictionalName;
}
public String getName() {
return fictionalName;
}
}
... and fall into a trap set by the original developer and their unusual use of the super keyword!
The code above isn't going to work - because in the original CleverDog implementation, getName() is invoked using the super keyword. That means it always invokes Dog.getName() - irrelevant of any overriding. Consequently, when you use your new DogOnTv type...
System.out.println("Showcasing the Clever Dog!");
CleverDog showDog = new CleverDog("TugBoat");
showDog.rollover();
showDog.speak();
System.out.println("And now the Dog on TV!");
DogOnTv dogOnTv = new DogOnTv("Pal", "Lassie");
dogOnTv.rollover();
... you get the wrong output:
Showcasing the Clever Dog!
Tugboat rolls over!
Tugboat speaks!
And now the Dog on TV!
Pal rolls over!
Pal speaks!
This is not the usual expected behavior when you override a method, so you should avoid creating this kind of confusion using the super keyword where it doesn't belong.
If, however, this is actually the behavior you want, use the final keyword instead - to clearly indicate that the method can't be overridden:
/* file CleverDog.java */
public class CleverDog extends Dog {
public CleverDog(String name) {
super(name);
}
public final String getName() { // final so it can't be overridden
return super.getName();
}
public void rollover() {
System.out.println(this.getName()+" rolls over!"); // no `super` keyword
}
public void speak() {
System.out.println(this.getName() + " speaks!"); // no `super` keyword
}
}
You are doing the right way by not using the super keyword for accessing getTyreCost.
But you should set your members private and only use the getter method.
Using super keyword should be reserved for constructors and overridden methods which need to explicitly call the parent method.
This would be dependent on how you plan to use the code. If you specify super.getTyreCost() and then later override that method. You will still be calling the method on the superclass, not the overridden version.
In my opinion, calling super is likely to lead to more confusion later on, so is probably best specified only if you have an explicit need to do so. However, for the case you have presented here - there will be no difference in behavior.
It depends on your needs and your desires. Using super forces the compile/application to ignore any potential methods in your current class. If you want to communicate that you only want to use the parent's method, then using super is appropriate. It will also prevent future modifications to your class to accidentally override the parent method thereby ruining your expected logic.
However, these cases are fairly rare. Using super everywhere within your class will lead to very confusing & cluttered code. In most general cases, just calling the method within your own class and allowing the compiler/jvm to determine which method (super or local) needs to be called is more appropriate. It also allows you to override/modify/manipulate the super's returning values cleanly.
If you use super, you are explicitly telling to use super class method (irrespective of sub class has overridden method or not), otherwise first jvm checks for the method in subclass (overridden method if any), if not available uses super class method.
overriding means redefining a method from the superclass inside a subclass with identical method signature. In your case, the getTyreCost() method has not been overridden, you have not redefined the method in your subclass, so no need to use super.getTyreCost(), only getTyreCost() will do(just like super.getTyreCost() will do the same way). super keyword is used when a method has been overridden, and you want a method call from within your subclass to be implemented in the superclass.
Technically, the one that's invoked in this case is the inherited version, for which the implementation is actually provided by the parent class.
There can be scenarios where you must use the super keyword. e.g. if Car had overridden that method, to provide a different implementation of itself, but you needed to invoke the implementation provided by the parent class then you would have use the super keyword. In that case, you could not afford to omit the super keyword because if you did then you would be invoking the implementation provided by the child class itself.
It is advised that further changes to the inherited class will not necessitate addition of the super qualifier and also prevent errors if missed.

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.

Categories