抽象如何帮助隐藏 Java 中的实现细节? [英] How does abstraction help in hiding the implementation details in Java?

查看:26
本文介绍了抽象如何帮助隐藏 Java 中的实现细节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抽象是隐藏实现细节并只向用户展示功能的过程.

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

另一种方式,它只向用户显示重要的东西,隐藏内部细节.所以下面是一个创建抽象类并覆盖抽象方法的示例.但我不明白的是它是如何隐藏实现细节的?

Another way, it shows only important things to the user and hides the internal details. So below is an example where an abstract class is made and abstract methods are overridden. But the thing i didn't understand is how it is hiding the implementation details?

abstract class Bank
{    
   abstract int getRateOfInterest();    
} 

class SBI extends Bank
{    
 int getRateOfInterest()
  {
   return 7;
   }    
  }

class PNB extends Bank  
{    
 int getRateOfInterest()
   { 
    return 8;
   }    
 }    

class TestBank{    
public static void main(String args[])
{    
 Bank b;   
 b=new SBI();  
 System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");    
 b=new PNB();  
 System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");    
 }
 }     

推荐答案

代码中的抽象就是抽象类本身:

The abstraction in your code is the abstract class itself:

abstract class Bank {    
   abstract int getRateOfInterest();    
} 

剩下的就是实现(和实现细节),具体来说:PNBSBI

and the rest is the implementation (and the implementation details), specifically: classes PNB and SBI

但我不明白的是它是如何隐藏实现细节的?

But the thing i didn't understand is how it is hiding the implementation details?

假设您有一个银行比较引擎,它由 BankComparisonEngine 类表示.它只会将 Bank(抽象 类)作为参数,然后获取其利率并将其保存到其内部数据库中,如下所示:

Imagine you have a bank comparison engine, which is represented by the BankComparisonEngine class. It will just take a Bank (abstract class) as an argument, then get its interest rate and save it to its internal database, like so:

class BankComparisonEngine {
  public void saveInterestRateOf(Bank bank) {
    int rate = bank.getRateOfInterest();
    // Save it somwehere to reuse later 
  }
}

具体的实现细节是如何隐藏的?好吧,BankComparisonEngine 并不知道 Bank 的具体实现的 getRateOfInterest() 方法是如何工作的(即:PNB.getRateOfInterest()SBI.getRateOfInterest() 已实现).它只知道它是一个返回 int 的方法(并且它应该返回一个利率).实现细节隐藏在扩展抽象类Bank的具体类中.

How are the implementation details hidden exactly? Well, BankComparisonEngine does not know how getRateOfInterest() method of a concrete implementation of Bank works (that is: PNB.getRateOfInterest() or SBI.getRateOfInterest() is implemented). It only knows it is a method that returns an int (and that it should return an interest rate). The implementation details are hidden inside the concrete classes that extend abstract class Bank.

这篇关于抽象如何帮助隐藏 Java 中的实现细节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆