Why does OpenJDK place private methods into vtable? - jvm

It seems that openJDK 8 places private methods which are not final nor static into vtable. Why is it so when dynamic binding is not used for private methods (since they're invoked with invokespecial) or is it used?

This is done to handle some rare situations when an overridable method with the same name and signature exists in a superclass. Though there is definitely a place for improvement, may be, targeted for JDK 9.
See https://bugs.openjdk.java.net/browse/JDK-8024368
Private methods always get a vtable entry to handle backward
compatibility with classes - i.e. you can have the same name of a
private method local to your class and also inherit a method of from
your superclass, which will get inherited around the private method,
by your child.

Related

Is there a solution to "Cannot access '<init>': it is private in XYZ?

I included a library I'd like to use, but in accessing to one of its classes I get the error message,
"Cannot access '<init>': it is private in [class name]
Is there something I can do to rectify this on my side, or am I just stuck to not use the package?
The error means the constructor is private. Given your comment, I'm assuming you're using a library. If this is the case, you'll have to find a different way to initialize it. Some libraries have factories or builders for classes, so look up any applicable documentation (if it is a library or framework). Others also use the singleton pattern, or other forms of initialization where you, the developer, don't use the constructor directly.
If, however, it is your code, remove private from the constructor(s). If it's internal and you're trying to access it outside the module, remove internal. Remember, the default accessibility is public. Alternatively, you can use the builder pattern, factory pattern, or anything similar yourself if you want to keep the constructor private or internal.
I came across this issue when trying to extend a sealed class in another file. Without seeing the library code it is hard to know if that is also what you are attempting to do.
The sealed classes have the following unique features:
A sealed class can have subclasses, but all of them must be declared in the same file as the sealed class itself.
A sealed class is abstract by itself, it cannot be instantiated directly and can have abstract members.
Sealed classes are not allowed to have non-private constructors (their constructors are private by default).
Classes that extend subclasses of a sealed class (indirect inheritors) can be placed anywhere, not necessarily in the same file.
For more info, have a read at https://www.ericdecanini.com/2019/10/14/kotlins-sealed-class-enums-on-steroids/
Hopefully, this will help others new to Kotlin who are also encountering this issue.
Class constructors are package-private by default. Just add the public keyword before declaring the constructor.
By default constructor is public so need to remove internal keyword.

Private constructor or private function?

I have a class with two constructors that share a bit of common functionality. They also have their own specific bit of functionality.
I was thinking of creating a private method and calling it from both constructors. Should this method be a private constructor?
If this method is a common constructor behavior - then IMO - yes, it will make the code more readable.
A common usage is for example (java syntax):
MyClass() {
this(SOME_DEFAULT_VALUE);
}
MyClass(int x) { ... }
Sometimes you have to write this method as a constructor, if for example (again java) it sets a final field, which cannot be modified in a method.
Both your constructors need a method, I guess before (or after) the have performed different operations. It does not have to be a constructor itself. It could, and in my opinion it should (at least as far as I can understand from your question), by a private method.

Proper use of private constructors

I was reading about private constructor and found a few points that I couldn't understand. It said, if you declare a constructor as private:
That class cannot be explicitly instantiated from another class
That class cannot be inherited
Should be used in classes containing only static utility methods
My first question: Point 2 says the class cannot be inherited. Well, if you declare a class private then it would still satisfy this property. Is it because, if a class is private, it can still be explicitly instantiated from outside by another class?
My second question: I don't understand point 3. If I have a helper class which is full of static methods, I would never have to instantiate that class to use the methods. So, what is the purpose of a constructor in that class which you are never going to instantiate?
Answer for Java
Question 1 You're confusing a private class, with a class that has a private constructor. Private constructors are used mainly for static classes that are not meant to be instatiated (i.e. they just have a bunch of static methods on them).
Question 2 Exactly there is no need for a constructor so you have to explicitly create a private constructor so that it does not get a default constructer that the JVM will provide if none is defined
An empty class with no methods defined will always be given a no argument constructor by the JVM by default
I take java and c++ as an examples (not the best OO languages known, but very popular) - since you are not defining which languge do you mean.
Ad.2. In these languages you must either call superclass constructor explicitly or it is implicitly called for you. From a subclass you cannot call private methods (only public and protected) - this rule applies to constructors as well. This means if the class has only private constructors, there is no way to call one in subclass constructor. So you cannot subclass such class.
Ad. 3. It is just to avoid confusion - since this class is only a container for utility methods, there is no point in instantiating it. This way you can enforce this rule at compile time.

When to declare methods as private

I am looking for specific and exact rules to determine how a method's visibility can be declared. This is not language agnostic, it applies to the standard OOP languages.
A good rule to follow would be:
Members should not have more accessibility than they need.
Start with private and make them more accessible as the need arises.
Basically:
Public is for when the method must be accessible by an outside class. Something like getState() would fit here.
Private is for when the method should not be accessible by any other class, something like changeState(...). Generally this relates to the actual alteration of an object's contents - maybe you'll have a public setX(int x) that just calls the private setXInternal(int x), that way you can have extra type-checking/safety/etc. To be safe you might as well make everything private until it has to be otherwise.
Protected is basically "public to child classes, private otherwise". Could go either way.
With any class/object there are:
1. things it does (behaviours)
2. how it does them (implementation)
The world cares about the behaviour of your object. It shouldn't (often) care about how it achieves this behaviour under the hood. Keep implementation details private, and expose behaviours.
Any kind of operation which does not define behaviour of particular object directly but is useful during implementation of object's behaviour is a candidate for private member function.
I think the helpfulness of the public, protected and private keywords is just to make the code more clear.
So you would use public for the API of a class, private to make it clear how to do NOT extend a class and protected in every other case.
A common pragmatic approach is never use private and to use just public or protected.
Public for things that are part of the public API.
Protected for non-public functions that you want subclasses to be able to call.
Private if you don't want subclasses mucking around with said method (or to even know of its existence).
In C, C++, and C# don't forgot to mark a method virtual if you want a child class to be able to override it.

Can I stop C++/CLI from adding IDisposable to my ref class?

C++/CLI helpfully generates the IDisposable scaffolding for you when you implement a destructor on a ref class. Also, if you don't implement a destructor, but your class has a member variable which implements IDisposable, then IDisposable is again automatically implemented on your class. It's pretty helpful and much better than how IDisposable is handled in C#.
I have run into this behaviour when implementing a ref class that holds onto an msclr::com::ptr (a smart pointer that contains an RCW).
ref class Test /* : IDisposable added by the compiler */
{
msclr::com::ptr<IWhatever> _aComObject;
}
In my specific case, the COM object referenced by my class doesn't 'lock' some unmanaged resource, it effectively just uses up a bit of unmanaged memory that the CLR can't see. Therefore I would like to avoid confusing the users of my ref class by not implementing IDisposable the class. Instead I want to make the CLR aware of the existence of the COM object by using the GC API to add the appropriate memory pressure.
So, the question is: is there a way to suppress implementation of IDisposable on a ref class that doesn't implement a destructor, but does hold an IDisposable member variable?
NB: often this would be the wrong thing to do, as it would prevent users of the class from deterministically disposing of the underlying COM object, but given the particular circumstances, exposing IDisposable has the potential to confuse users of my ref class, since it really is not necessary to Dispose of the ref class in question.
I suppose one option would be to implement a variant of msclr::com::ptr without a destructor.
Any other method to suppress the automatic addition of IDisposable would be appreciated. Thanks.
Answer
Declare _aComObject as a handle to an msclr::com::ptr (msclr::com::ptr<IWhatever>^). The compiler does not then regard Test as being the 'owner' of the com ptr object, and does not Dispose it when Test is deleted.
I think the answer is to hold a handle to the msclr::com::ptr rather than holding it 'by value' (which is still holding it as a handle 'behind the scenes', except the C++CLI compiler treats it as a value - 'deleting' it (calling Dispose) when the owner object is deleted (Disposed)).
I'm not sure I agree with the ratioanle for avoiding the IDispose implementation -- but why not just store an IWhatever* in your class. The compiler shouldn't then generate the IDisposable implementation.
If you don't want the destructor behaviour then what benefit is the com::ptr wrapper buying you? You can always declare an com::ptr on the stack and assign your member pointer to it in any given method if you really need it.