快捷搜索:  as  2018  FtCWSyGV  С˵  test  xxx  Ψһ  w3viyKQx

和记娱乐网上官网:Java面向对象编程实例详解



Java是一种面向工具的说话,是实现面向工具编程的强大年夜对象。但若何在编程中实际运用并发挥其最大年夜效能呢?本文经由过程一个实际Java法度榜样的开拓历程,具体阐清楚明了若何应用面向工具实现Java编程。

我们要实现的Java利用法度榜样是:当用户输入一个球体的半径,法度榜样将显示该球体的体积与外面积。在您涉猎下文曩昔,请您自己思虑一分钟,您将若何设计该Java利用法度榜样。

一、通俗实现措施

我信托大年夜多半法度榜样员要实现上述功能的法度榜样,异常迅速地、自大地将采纳下面的实今世码:

class Sphere

{

public static void main(String[] args)

{

EasyReader console = new EasyReader();

System.out.print("Enter the radius: ");

double radius = console.readDouble();

System.out.println("Radius = " + radius);

double volume = 4.0 / 3.0 * Math.PI * radius * radius * radius;

System.out.println("Volume = " + volume);

double surfArea = 4.0 * Math.PI * radius * radius;

S和记娱乐网上官网ystem.out.println("Surface area = " + surfArea);

}

}

EasyReader类代码如下:

import java.io.*;

public class EasyReader

{

protected String myFileName;

protected BufferedReader myInFile;

protected int myErrorFlags = 0;

protected static final int OPENERROR = 0x0001;

protected static final int CLOSEERROR = 0x0002;

protected static final int READERROR = 0x0004;

protected static final int EOF = 0x0100;

/**

* Constructor. Prepares console (System.in) for reading

*/

public EasyReader()

{

myFileName = null;

myErrorFlags = 0;

myInFile = new BufferedReader(

new InputStreamReader(System.in), 128);

}

/**

* Constructor. opens a file for reading

* @param fileName the name or pathname of the file

*/

public EasyReader(String fileName)

{

myFileName = fileName;

myErrorFlags = 0;

try

{

myInFile = ne和记娱乐网上官网w BufferedReader(new FileReader(fileName), 1024);

}

catch (FileNotFoundException e)

{

myErrorFlags |= OPENERROR;

myFileName = null;

}

}

/**

* Closes the file

*/

public void close()

{

if (myFileName == null)

return;

try

{

myInFile.close();

}

catch (IOException e)

{

System.err.println("Error closing " + myFileName + "

");

myErrorFlags |= CLOSEERROR;

}

}

/**

* Checks the status of the file

* @return true if en error occurred opening or reading the file,

* false otherwise

*/

public boolean bad()

{

return myErrorFlags != 0;

}

/**

* Checks the EOF status of the file

* @return true if EOF was encountered in the previous read

* operation, false otherwise

*/

public boolean eof()

{

return (myErrorFlags & EOF) != 0;

}

private boolean ready() throws IOException

{

return myFileName == null || myInFile.ready();

}

/**

* Reads the next character from a file (any character including

* a space or a newline character).

* @return character read or 〈code〉null〈/code〉 character

* (Unic和记娱乐网上官网ode 0) if trying to read beyond the EOF

*/

public char readChar()

{

char ch = ´u0000´;

try

{

if (ready())

{

ch = (char)myInFile.read();

}

}

catch (IOException e)

{

if (myFileName != null)

System.err.println("Error reading " + myFileName + "

");

myErrorFlags |= READERROR;

}

if (ch == ´u0000´)

myErrorFlags |= EOF;

return ch;

}

/**

* Reads from the current position in the file up to and including

* the next newline character. The newline character is thrown away

* @return the read string (excluding the newline character) or

* null if trying to read beyond the EOF

*/

public String readLine()

{

String s = null;

try

{

s = myInFile.readLine();

}

catch (IOException e)

{

if (myFileName != null)

System.err.println("Error reading " + myFileName + "

");

myErrorFlags |= READERROR;

}

if (s == null)

myErrorFlags |= EOF;

return s;

}

/**

* Skips whitespace and reads the next word (a string of consecutive

* non-whitespace characters (up to but excluding the next space,

* newline, etc.)

* @return the read string or null if trying to read beyond the EOF

*/

public String readWord()

{

StringBuffer buffer = new StringBuffer(128);

char ch = ´ ´;

int count = 0;

String s = null;

try

{

while (ready() && Character.isWhitespace(ch))

ch = (char)myInFile.read();

while (ready() && !Character.isWhitespace(ch))

{

count++;

buffer.append(ch);

myInFile.mark(1);

ch = (char)myInFile.read();

};

if (count 〉 0)

{

myInFile.reset();

s = buffer.toString();

}

else

{

myErrorFlags |= EOF;

}

}

catch (IOException e)

{

if (myFileName != null)

System.err.println("Error reading " + myFileName + "

");

myErrorFlags |= READERROR;

}

return s;

}

/**

* Reads the next integer (without validating its format)

* @return the integer read or 0 if trying to read beyond the EOF

*/

public int readInt()

{

String s = readWord();

if (s != null)

return Integer.parseInt(s);

else

return 0;

}

/**

* Reads the next double (without validating its format)

* @return the number read or 0 if trying to read beyond the EOF

*/

public double readDouble()

{

String s = readWord();

if (s != null)

return Double.parseDouble(s);

// in Java 1, use: return Double.valueOf(s).doubleValue();

else

return 0.0;

}

}

以下是法度榜样的输出结果画面。

screen.width-333)this.width=screen.width-333;">

在上述法度榜样中,实现了球体外面积和体积的算法,并经由过程EasyReader类轻松实现了节制台的输入,然则该法度榜样只是完成了法度榜样所要求的功能,并谋略出了却果。该法度榜样不是一个好的设计法度榜样,它既没采纳布局化编程,也没有发挥Java说话的强大年夜效能,更不是面向工具编程。

实际上,从法度榜样设计的角度来看,以上法度榜样是一个异常糟糕的设计法度榜样。首先,用户界面与谋略公式混杂在一路。请记着:对付任何编程说话,用户界面必须与谋略或处置惩罚历程分分开来。别的,输出的结果太丢脸,数值包括太多的小数。

二、布局化编程措施

在以下的法度榜样代码中,我们添加了2个措施,分手实现球体外面积与体积的谋略,并经由过程响应的类节制数值的输出款式。

import java.text.DecimalFormat;

class Sphere

{

// Computes the volume of a sphere with radius r.

private static double volume(double r)

{

return 4.0 / 3.0 * Math.PI * r * r * r;

}

// Computes the surface area of a sphere with radius r.

private static double surfaceArea(double r)

{

return 4.0 * Math.PI * r * r;

}

public static void main(String[] args)

{

EasyReader console = new EasyReader();

System.out.print("Enter the radius: ");

double radius = console.readDouble();

DecimalFormat f3 = new DecimalFormat("0.000");

System.out.println(); // displays a blank line

System.out.println("Radius = " + f3.format(radius));

System.out.println("Volume = " + f3.format(volume(radius)));

System.out.println("Surface area = " + f3.format(surfaceArea(radius)));

System.out.println();

}

}

以下是输出结果。

screen.width-333)this.width=screen.width-333;">

上述颠末改动后的法度榜样,其输出结果看起来漂亮多了,但它仍只是一个勉强可以经由过程的设计法度榜样。该法度榜样采纳了布局化编程的风格,并不是面向工具编程。首先,谋略历程仍与用户界面实现在同一个类中。别的,对付不合的用户界面,不能表现出面向工具编程的好处,即不能重用这些谋略历程。

三、面向工具编程措施

要实现上述法度榜样的面向工具编程,我们必须留意:Java利用法度榜样中的每一个类或工具,必须零丁实现自己的义务。详细来说,在本法度榜样中,一个类定义球体,即模型或数据表示(Model),另一个类便是实现用户界面(UI)。

别的更紧张的,也是中公法度榜样员经常漠视的,便是要斟酌到团体的开拓与治理,实现面向工具编程,便是闪开拓组中的每个法度榜样员能自力开拓不合的类,异常迅速地前进开拓效率。

是以,对付本法度榜样来说,面向工具编程的设计措施便是将Model与UI分手是实现在不合的类中。其示意图如下:

screen.width-333)this.width=screen.width-333;">

以下分手是该法度榜样的UML类图设计与法度榜样代码。有关UML类图的设计与利用,请查阅作者的另文(《使用UML类图设计Java利用法度榜样详解一、二》)

Sphere的类图设计为:

screen.width-333)this.width=screen.width-333;">

其代码为:

class Sphere

{

private double myRadius;

private double myCenterX;

private double myCenterY;

// Constructors:

public Sphere (double x, double y, double r)

{

myCenterX = x;

myCenterY = y;

myRadius = r;

}

// etc...

// Accessors and modifiers:

public double getRadius()

{

return myRadius;

}

public void setRadius(double r)

{

myRadius = r;

}

// etc...

// Other public methods:

public double volume()

{

return 4.0 / 3.0 * Math.PI * myRadius * myRadius * myRadius;

}

public double surfaceArea()

{

return 4.0 * Math.PI * myRadius * myRadius;

}

public String toString()

{

return "Sphere [Center = (" + myCenterX + ", " + myCenterY + ") Radius = " + myRadius

+ "]";

}

}

TestSphere的类图为:

screen.width-333)this.width=screen.width-3和记娱乐网上官网33;">

着实今世码为:

import java.text.DecimalFormat;

class TestSphere

{

public static void main(String[] args)

{

EasyReader console = new EasyReader();

System.out.print("Enter the radius: ");

double radius = console.readDouble();

DecimalFormat f3 = new DecimalFormat("0.000");

Sphere balloon = new Sphere(0, 0, radius);

System.out.println();

System.out.println(balloon);

System.out.println("Volume = " + f3.format(balloon.volume()));

System.out.println("Surface area = " + f3.format(balloon.surfaceArea()));

System.out.println();

}

}

该法度榜样的种种之间的互相关系可以表示为:

screen.width-333)this.width=screen.width-333;">

该法度榜样的UML序列图可以表示如下。有关UML序列图的设计与利用,请查阅作者的另文(《使用UML序列图设计Java利用法度榜样详解》)

screen.width-333)this.width=screen.width-333;">

以下是法度榜样的输出结果。

screen.width-333)this.width=screen.width-333;">

四、设计图形用户界面(GUI)

以上法度榜样使用面向工具编程的设计措施,较好地实现了Java利用法度榜样。但美中不够的是,没有图形用户界面供用户应用。

假如我们要增添设计图形用户界面,我们就可以将类Sphere交给一个法度榜样员去实现,将用户界面SphereWindow交给别的一个法度榜样员去开拓,这便是面向工具编程的好处,可以进行团队开拓,而不是作坊式的传统的法度榜样开拓要领。

以下是用户界面SphereWindow的实今世码:

import java.a和记娱乐网上官网wt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.border.*;

import java.text.DecimalFormat;

public class SphereWindow extends JFrame

implements ActionListener

{

private JTextField radiusIn, volumeOut, surfAreaOut;

private Sphere balloon;

private DecimalFormat f3 = new DecimalFormat("0.000");

public SphereWindow()

{

super("Spheres: volume and surface area");

JPanel view = new JPanel();

view.setLayout(new GridLayout(6, 2, 10, 10));

view.setBorder(new EmptyBorder(10, 10, 10, 10));

view.add(new JLabel("Radius = ", SwingConstants.RIGHT));

radiusIn = new JTextField(8);

radiusIn.setBackground(Color.yellow);

radiusIn.addActionListener(this);

view.add(radiusIn);

view.add(new JLabel("Volume = ", SwingConstants.RIGHT));

volumeOut = new JTextField(8);

volumeOut.setEditable(false);

volumeOut.setBackground(Color.white);

view.add(volumeOut);

view.add(new JLabel("Surface area = ", SwingConstants.RIGHT));

surfAreaOut = new JTextField(8);

surfAreaOut.setEditable(false);

surfAreaOut.setBackground(Color.white);

view.add(surfAreaOut);

view.add (new JPanel()); // reserved

Container c = getContentPane();

c.add(view, BorderLayout.CENTER);

balloon = new Sphere(0,0,100);

}

public void actionPerformed(ActionEvent e)

// Called automatically when the user

// strikes Enter on the input field

{

String s = radiusIn.getText();

double r = Double.parseDouble(s);

balloon.setRadius(r);

radiusIn.setText(" " + f3.format(r));

volumeOut.setText(" " + f3.format(balloon.volume()));

surfAreaOut.setText(" " + f3.format(balloon.surfaceArea()));

}

public static void main(String[] args)

{

SphereWindow w = new SphereWindow();

w.setSize(300, 250);

w.addWindowListener(new ExitButtonListener());

w.show();

}

}

ExitButtonListener类的代码为:

import java.awt.event.*;

public class ExitButtonListener extends WindowAdapter

{

public void windowClosing(WindowEvent e)

{

System.exit(0);

}

}

经由过程实现上述法度榜样,使用面向工具编程的设计措施,我们将Model(模型,这里是Sphere)与view(视图,这里是SphereWindow)分分开来。并较好地实现了类的封装,类的重用(Sphere)。便于团队开拓,迅速前进开拓效率。

摘自:ZDnet   光阴:2003年9月10日

您可能还会对下面的文章感兴趣: