- private:被声明为 private 的属性或方法,只能在当前类中被访问。
- 缺省:若一个类、属性或方法没有声明任何访问修饰符,可被同一包中的其它类访问。
- protected:被声明为 protected 的属性或方法,既可以被同一包中的其他类访问,也可以被不同包中的子类访问。
- public:被声明为 public 的类、属性或方法,可被同一包或不同包的所有类访问。
父类 private 修饰的内容是被继承的,只不过不可见
//子类,什么都没写
public class Son extends Father
{
}
public class Father
{
private void method()
{
System.out.println("父类private的方法");
}
public static void main(String[] args)
{
Father father = new Son();
father.method();
}
}
https://blog.csdn.net/ql_7256/article/details/107428016
public class Parent
{
private void mehotd1()
{
System.out.println("父类中的私有方法");
}
}
public class Child extends Parent
{
}
import java.lang.reflect.Method;
/**
* @author ql
* @date 2020/10/30
* @time 17:32
**/
public class Test01
{
// 采用了两种不同的方式获取了这个方法对象,不过原理都差不多
public static void main(String[] args) throws Exception
{
test01();
test02();
}
public static void test01() throws Exception
{
Class parentClass = Parent.class;
Method mehotd1 = parentClass.getDeclaredMethod("mehotd1");
//System.out.println(mehotd1);
mehotd1.setAccessible(true);
Child child = new Child();
mehotd1.invoke(child);
}
public static void test02() throws Exception
{
Child child = new Child();
Class superclass = child.getClass().getSuperclass();
Method mehotd1 = superclass.getDeclaredMethod("mehotd1");
//System.out.println(method01);
mehotd1.setAccessible(true);
mehotd1.invoke(child);
}
}
此时用反射来获取方法然后在子类中调用,仍然可以,说明确实是继承下来了,不过是可见性设置成了 false 而已