Java 中的私有方法

Sheeraz Gul 2023年10月12日
Java 中的私有方法

Java 中的私有方法有一个私有访问修饰符,这意味着它们对定义类的访问受到限制,并且在继承的子类中不可访问;这就是为什么他们没有资格覆盖。

但是,可以在子类中创建一个方法,并且可以在父类中访问该方法。本教程演示了如何在 Java 中创建和使用私有方法。

Java 中的私有方法

如上所述,私有方法只能在定义类中访问;对于私有方法,我们考虑以下几点。

  1. 私有方法是 Class X,只能在 Class X 中访问。
  2. 包 X 的包私有成员或方法只能在 X 包的所有类中访问。

让我们尝试在 Java 中创建和使用私有方法。参见示例:

package delftstack;

public class Private_Methods {
  private void print() {
    System.out.println("The Private Method can only be printed in the defining Class");
  }
  public static void main(String[] args) {
    Private_Methods Demo = new Private_Methods();
    Demo.print();
    Private_Methods_Child Demo1 = new Private_Methods_Child();
    Demo1.print();
  }
}
class Private_Methods_Child extends Private_Methods {
  public void print() {
    System.out.println("The Public Method can be printed anywhere");
  }
}

上面的代码创建了一个私有方法并在同一个类中调用它,同时也创建了一个公共方法在父类中调用它;输出将是:

The Private Method can only be printed in the defining Class
The Public Method can be printed anywhere

如果我们在子类中将 public 方法改为 private,就会抛出异常。参见示例:

package delftstack;

public class Private_Methods {
  private void print() {
    System.out.println("The Private Method can only be printed in the defining Class");
  }
  public static void main(String[] args) {
    Private_Methods Demo = new Private_Methods();
    Demo.print();
    Private_Methods_Child Demo1 = new Private_Methods_Child();
    Demo1.print();
  }
}
class Private_Methods_Child extends Private_Methods {
  private void print() {
    System.out.println("The Public Method can be printed anywhere");
  }
}

我们无法从子类访问 print 方法。见输出:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
	The method print() from the type Private_Methods_Child is not visible

	at delftstack.Private_Methods.main(Private_Methods.java:11)
作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

相关文章 - Java Method