Herança e Composição/Exercício 02: Porta AND Ternária

From Wiki**3

< Herança e Composição
Revision as of 01:26, 5 November 2018 by Root (talk | contribs)

Problema

Defina uma nova classe que represente uma porta lógica AND com três entradas. Esta classe deve chamar-se AndGate3 e apresenta a mesma funcionalidade que a de duas entradas. A apresentação (toString) é A: valor B: valor C: valor.

A classe AndGate3 deve ser definida reutilizando o conceito AndGate2 (definido no Exercício 1).

Adapte a função main definida anteriormente, por forma a integrar alguns testes com a nova porta lógica.

Solution 1: AndGate3i defined as a subclass of AndGate2

In this solution we observe that the operation is a specialization of the previous one. This allows us to reuse the previous functionality.

Ficheiro AndGate3i.java
 1 /** Logical AND gate (inheritance). */
 2 public class AndGate3i extends AndGate2 {
 3 	/** A new input is needed (the other two are inherited). */
 4 	private boolean _c = false;
 5 
 6 	/**
 7 	 * Default constructor: false for all inputs.
 8 	 */
 9 	public AndGate3i() {
10 		//super(); //default: explicit call not needed
11 	}
12 
13 	/**
14 	 * Inputs receive same value.
15 	 * 
16 	 * @param v
17 	 *            the input value.
18 	 */
19 	public AndGate3i(boolean v) {
20 		super(v);
21 		_c = v;
22 	}
23 
24 	/**
25 	 * Arbitrary input value combinations.
26 	 * 
27 	 * @param a
28 	 *            input value
29 	 * @param b
30 	 *            input value
31 	 * @param c
32 	 *            input value
33 	 */
34 	public AndGate3i(boolean a, boolean b, boolean c) {
35 		super(a, b);
36 		_c = c;
37 	}
38 
39 	/**
40 	 * @return third input value.
41 	 */
42 	public boolean getC() {
43 		return _c;
44 	}
45 
46 	/**
47 	 * Set input value.
48 	 * 
49 	 * @param c
50 	 *            input value.
51 	 */
52 	public void setC(boolean c) {
53 		_c = c;
54 	}
55 
56 	/**
57 	 * @return value of logical AND operation.
58 	 */
59 	@Override
60 	public boolean getOutput() {
61 		return super.getOutput() && _c;
62 	}
63 
64 	/**
65 	 * @see java.lang.Object#equals(java.lang.Object)
66 	 */
67 	@Override
68 	public boolean equals(Object other) {
69 		if (other instanceof AndGate3i) {
70 			AndGate3i andGate = (AndGate3i) other;
71 			return super.equals(other) && _c == andGate.getC();
72 		}
73 		return false;
74 	}
75 
76 	/**
77 	 * @see java.lang.Object#toString()
78 	 */
79 	@Override
80 	@SuppressWarnings("nls")
81 	public String toString() {
82 		return super.toString() + " C:" + _c;
83 	}
84 }

Solução 2: AndGate3c defined as a composition of two AndGate2

In this solution, the 3-input gate is defined as a composition of 2-input gates. Note that the A-input of the second gate is updated whenever the inputs of the first gate are changed.

Ficheiro AndGate3c.java
{{{2}}}