why can't we assign weaker privilege in subclass

why can't
why can't i liz phair movie
why can't i meaning
why can't we be friends
why can't i lyrics
why can't you grammar
liz phair - extraordinary
the cure why can't i be you blackface

I have a class which has a method whose access specifier by default is public. Now, I would like to extend this class in a subclass and I want to override this method to have access specifier "private". When compiling this code, I am getting a compilation error:

"attempting to assign weaker access privileges".

Could somebody please explain to me what is wrong with assigning weaker privileges in a subclass?

Here is the code that caused the compilation error:

class Superclass 
{
    void foo() 
    {
        System.out.println("Superclass.foo");
    }
}

class Subclass extends Superclass 
{
    private void foo() 
    {
        System.out.println("Subclass.foo");
    }
}

The short answer is that it is not allowed because it would break type substitutability; see also the Liskov Substititution Principle (LSP).

The point is that polymorphism in Java (and other programming languages) relies on you being able to treat an instance of a subclass as if it was an instance of the superclass. But if the method is restricted in the subclass, you find that the compiler cannot figure out whether the access rules allow a method to be called ...

For instance, lets assume that your example code was legal:

// Assume this code is in some other class ...

SuperClass s1 = new SuperClass();

s1.foo();                          // OK!

SuperClass s2 = new Subclass();

s2.foo();                          // What happens now?

SuperClass s3 = OtherClass.someMethod();

s3.foo();                          // What happens now?

If you base the decision on whether s2.foo() is allowed on the declared type of s2, then you allow a call to a private method from outside the abstraction boundary of Subclass.

If you base the decision on the actual type of the object that s2 refers to, you cannot do the access check statically. The s3 case makes this even clearer. The compiler has absolutely no way of knowing what the actual type of the object returned by someMethod will be.

Access checks that could result in runtime exceptions would be a major source of bugs in Java application. The language restriction under discussion here avoids this nasty problem.

Why Can't It Be - Kaye Cal (Lyrics), We understand that this can be frustrating, so please keep in mind that you'll receive a notification at the top of the group indicating when you'll be able to post​  When you get a message that says Windows can't be activated, there are several possible reasons why. Select any of the following topics to see some typical reasons for activation difficulty, along with possible ways to get going again.

You can't restrict access because you have already allowed more access in the super class. e.g.

SuperClass sc = new SubClass();
sc.foo(); // is package local, not private.

The access of sc is determined by the type of the reference sc not what it references because it is impossible for the compiler to know in all cases what type the object is at run time. For this to be a safe assumption the sub-class must honour the contract given by the parent or it fails to be a valid subclass. This is no different to the parent saying a method is implemented but the sub class saying it is not (or not accessible)

You could work around this by saying you can only access the sub-class method via the parent, not directly. The problem with this is you don't know when a parent might add a method and when you make a method private you do this because you want it to be private, and not accessible another way.

BTW You can still access a private method via reflection which has the side effect that it cause all sort of problems for the JVM. e.g. it has to keep private methods even though it might determine there is no way it can be called normally.

In short, you want code which means what it says, and not have a split personality. It is either package local or it is private not something sort of in between but not really either. This is not such a problem the other way. i.e. if the sub class is public. It just means the sub-class can be used in more places than the parent, just like it can implement more methods.

Smash Mouth, Why Is My Post Type Unsupported? Why is my boost unavailable? To learn more about why your boost is unavailable or how you can boost a similar post,  Being overweight, getting too little exercise, and smoking all can work against the good blood flow that is key to erections. For some men, a little alcohol may help take the edge off.

If this were allowed, there would be a backdoor through which you could call methods that should not be accessible.

Lets say that this is allowed

class Super {  
    public void method() {  
        System.out.println("Super");  
    }  
}


class Sub extends Super {  
    // This is not allowed, but suppose it was allowed  
    protected void method() {  
        System.out.println("Sub");  
    }  
}

// In another class, in another package:  
Super obj = new Sub();  
obj.method();

obj.method would be possible, because method() is public in class Super. But it should not be allowed, because obj is really referring to an instance of Sub, and in that class, the method is protected!

To restrict a call to a method in class Sub that should not be accessible from the outside, this restriction is put.

Curious Kids: why can't we do whatever we want?, Bitcoin is touted as a private, decentralized digital currency. But what gives the leading cryptocurrency value? “Why Can’t We Be Friends?” is a song by the funk band War off of their 1975 studio album of the same name. The song reached #6 on the Billboard Hot 100 in the summer of 1975.

Constricting the access modifier of a super class method is an invalid override because it's breaking the super-class contract and invalidates the substitution principle i.e. a sub-class object IS-A super-class object as well.

public void doSomething(SuperClass sc) {
  sc.publicMethodInSuperClass();
}

doSomething(new SubClass()); // would break

If this was allowed, the above client code would break because your SubClass doesn't have that method public.

Reference: Liskov substitution principle

Why can't I post in a Facebook group?, Note: You may have to adjust the tracker into the correct position in the charging cable. Troubleshooting. I can't set up Charge 4: the screen is  ELECTIONS IN the United States have been thrown into disarray by a pandemic that makes packing into polling places a risk the country cannot afford to take.

Apart from the obvious problems with using such a constructions(as pointed out by Peter Lawrey in his answer), read about the theory behind it as well: LSP, which means you must be able to substitute the main type with its subclass.

Boost Unavailable on Facebook, The long read: It's not about foreign trolls, filter bubbles or fake news. Technology encourages us to believe we can all have first-hand access to  A reader does not understand why her children take issue with her nostalgia for Civil War iconography. By Philip Galanes Thanks to political correctness, I can no longer converse freely with my

Why Do Bitcoins Have Value?, Astronomers would later discover just a single Earthlike planet in its dataset. A decade later, researchers are finally closing in on some of the  Why Can After Hours Trading Help You In The Stock Market? After hours trading presents a unique risk and reward proposition. On the one hand, it allows you to trade on news events before many

Help article: Why can't I set up my Fitbit device?, Can’t go? You’re not alone. About 20% of Americans have occasional constipation-- bowel movements less than three times a week.Or if they do poop, the output is hard, small, and painful to

Why can't we agree on what's true any more? | Media, There could be several reasons why you aren't receiving your e-mail messages. Please review the following situations to see if one applies to you: Did you just move your domain name to Network Solutions® or register a new domain name? If so, it will take approximately 12-36 hours for the domain name information to propagate to servers worldwide.

Comments
  • Interesting question! This very case is allowed in C++.
  • "I have a class which has a method whose access specifier by default is public". Actually the default access specifier is not public. If you did't mentioned any specific access specifier then it is 'default' :).
  • @quamrana And what happens in C++ when you acces an object through a superclass-typed variable? The compiler surely lets it through... does it error out at runtime?
  • @StephenC +1 I was trying to tease out that statement from quamrana :)
  • In the case of C++ and the example above (lets say public in the base class, private in the derived class) access only depends on the pointer you have at hand. There are no runtime errors, only compile-time errors (accessing private method from outside the class).
  • Yes, but why must that be (is what he's asking)?
  • "The only reason I can think of to have this restriction is that when a subclass derives from an interface, as a client programmer, you expect to be able to call all the accessible methods of the interface from a reference to the derived class." - That's basically LSP. Because, if the client programmer cannot do that, then the subclass cannot be substituted for the parent class!
  • No its not. LSP refers to the client's perspective where they only know about the base class and expect the base class to work a certain way. When you supply a derived class to the client because your language allows it, then the derived class should behave the same way, such that the client function still works.
  • I think you are construing the LSP too narrowly. The Liskov & Wing definition is this: "Subtype Requirement: Let ϕ ( x ) be a property provable about objects x of type T. Then ϕ ( y ) should be true for objects y of type S where S is a subtype of T.". In this case, ϕ is having an accessible method foo. This is a property of SuperClass that clients depend on, and therefore also needs to be a property of SubClass ... or else an instance of the latter is not substitutable for an instance of the former. See en.wikipedia.org/wiki/Liskov_substitution_principle
  • You can add some example code to support explain more