创建一个方法是否被认为是一种抽象?
Is creating a method considered an abstraction?
假设我有这个方法
void print(String msg){
System.out.println(msg);
}
因为我创建了一个打印方法,所以我不必知道它是如何打印的,所以这被认为是一种抽象,还是我理解错了?
在某种程度上是的,这就是抽象,任何使用它的东西都不需要知道它是如何打印的,只需要知道它是如何打印的。一个更好的例子是使用 repo。
interface UserRepo {
public User getUserByUsername(final String username);
public User updateUser(final User user);
}
然后您针对界面进行编码。例如,如果使用 spring 依赖注入:
@Service
public class UserService {
@Resource
private UserRepo userRepo;
public void updateUserEmail(final String username, final String newEmail) {
final User user = userRepo.getUserByUsername(username);
user.setEmail(newEmail);
userRepo.updateUser(user);
}
UserService 不知道 repo 如何让用户保持原样,可能是使用数据库、平面文件或网络服务。
Here is some more info on Abstraction, with pictures!
Also this details the difference between abstraction and polymorphism
如果你创建这个方法只是为了隐藏底层实现的细节,那么它就是封装。
你的方法不是抽象的,因为它是一个具体的实现。只有在接口中定义签名或在抽象中定义为抽象方法时,才能将其称为抽象 class.
来自 java 教程:
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:
abstract void moveTo(double deltaX, double deltaY);
任何抽象的东西都可以存在于思想中或作为一个想法,但没有物理或具体的存在。当我在 google(https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=abstract%20definition).
中查找抽象的定义时出现了这个问题
假设我有这个方法
void print(String msg){
System.out.println(msg);
}
因为我创建了一个打印方法,所以我不必知道它是如何打印的,所以这被认为是一种抽象,还是我理解错了?
在某种程度上是的,这就是抽象,任何使用它的东西都不需要知道它是如何打印的,只需要知道它是如何打印的。一个更好的例子是使用 repo。
interface UserRepo {
public User getUserByUsername(final String username);
public User updateUser(final User user);
}
然后您针对界面进行编码。例如,如果使用 spring 依赖注入:
@Service
public class UserService {
@Resource
private UserRepo userRepo;
public void updateUserEmail(final String username, final String newEmail) {
final User user = userRepo.getUserByUsername(username);
user.setEmail(newEmail);
userRepo.updateUser(user);
}
UserService 不知道 repo 如何让用户保持原样,可能是使用数据库、平面文件或网络服务。
Here is some more info on Abstraction, with pictures!
Also this details the difference between abstraction and polymorphism
如果你创建这个方法只是为了隐藏底层实现的细节,那么它就是封装。
你的方法不是抽象的,因为它是一个具体的实现。只有在接口中定义签名或在抽象中定义为抽象方法时,才能将其称为抽象 class.
来自 java 教程:
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:
abstract void moveTo(double deltaX, double deltaY);
任何抽象的东西都可以存在于思想中或作为一个想法,但没有物理或具体的存在。当我在 google(https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=abstract%20definition).
中查找抽象的定义时出现了这个问题