Private methods can or cannot be overridden by public methods

For ruby

First of all, ruby.

ruby2.4


class Foo
  private
  def hoge
    p :hoge_in_Foo
  end
end

class Bar < Foo
  def hoge #Can be overridden without error
    p :hoge_in_Bar
  end
end

b = Bar.new
b.hoge # Bar#hoge is called

You can just override it. There is no warning. I think it will cause trouble.

For Java

For Java:

Foo.java


class Foo
{
  private void hoge(){ System.out.println( "hoge in Foo" ); }
}

Bar.java


class Bar extends Foo
{
  @Override
  public void hoge(){ //=>error:Methods do not override or implement supertype methods
    System.out.println( "hoge in Bar" );
  }
  public static void main( String[] args ){
    (new Bar()).hoge();
  }
}

If you do, an error will occur as described in the above comment. preferable. Foo's hoge isn't an overridable method in the first place, so it's natural. So, without " @ Override ", there will be no error or warning.

For C ++

c++11


#include <iostream>

class Foo
{
  private:
    virtual void hoge(){ std::cout << "hoge in Foo\n"; }
};
class Bar: public Foo
{
  public:
    virtual void hoge() override { std::cout << "hoge in Bar\n"; }
};

int main()
{
  Bar bar;
  bar.hoge(); // okay
}

Can be overridden normally. Of course, it can be overridden because Foo's hoge is virtual. However, I wonder if there is no warning even if the visibility is changed from private to public. In the first place, it's okay to give a warning when it's private and virtual.

Recommended Posts

Private methods can or cannot be overridden by public methods
Organize methods that can be used with StringUtils
[Ruby] Methods that can be used with strings