本文介绍了抽象如何帮助隐藏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();    
} 

,其余为实施(实施详细信息),具体是:类 PNB SBI

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

想象你有一个银行比较引擎,由 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()方法如何。 / code>有效(即:实现了 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中的实现细节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 23:42