java 在抽象类中使用私有方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5743853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
use of private method inside abstract class
提问by sandeep
What is the use of writing a private method inside an abstract class, and can we write public static inside that class? Please give an example.
在抽象类中编写私有方法有什么用,我们可以在该类中编写公共静态方法吗?请举例说明。
回答by Aaron Digulla
You can use any kind of method in an abstract class. The only difference between an abstract class and a normal one is that the abstract class contains methods which have no body:
您可以在抽象类中使用任何类型的方法。抽象类和普通类之间的唯一区别是抽象类包含没有主体的方法:
public abstract Foo {
public void foo() {
bar();
}
private void bar() {
doSomething();
}
protected abstract void doSomething();
}
So while bar()
has no idea what doSomething()
really does, it knows that it will exist eventually and how to call it.
因此,虽然bar()
不知道doSomething()
真正做什么,但它知道它最终会存在以及如何调用它。
This is enough for the compiler to create the byte code for the class.
这足以让编译器为类创建字节码。
回答by Jigar Joshi
we can have our implementation in abstract class and so the private method
我们可以在抽象类中实现我们的实现,因此私有方法
For Example :
例如 :
public abstract class AbstractDAO{
public void save(){
validate();
//save
}
private void validate(){ // we are hiding this method
}
}
回答by Djamel-eddine Bouzegzeg
But an abstract method can never be private , it must be public or protected , otherwise the subclass won't be able to define it
但是抽象方法永远不能是私有的,它必须是公共的或受保护的,否则子类将无法定义它