我需要在将子类发送到超类之前检查子类中接收的变量的值。
这就是我的超类
//superclass
public class Account
{
private double balance;
public Account( double amount )
{
balance = amount;
}
public Account()
{
this(0.0);
}
public void deposit( double amount )
{
balance += amount;
}
public void withdraw( double amount )
{
balance -= amount;
}
public double getBalance()
{
return balance;
}
}
这就是我的子类
public class SafeAccount extends Account
{
public SafeAccount(double amount)
{
// something to check if amount is positive before sending it to
super
// if it's not positive, use no argument constructor to set balance ==
0.0
}
}
我想我应该使用"这个(金额)"以某种方式检查它,但我不确定这将如何工作。
答案 0 :(得分:4)
super()
必须是构造函数体中的第一个语句,因此您无法在它之前执行检查。
简单的解决方法:
public class SafeAccount extends Account
{
public SafeAccount(double amount)
{
super(Math.max(0.0, amount));
}
}
如果你真的必须使用no arg构造函数,那么更复杂的解决方法是:
public class Account {
Account() {
}
Account(double x) {
}
}
public class SafeAccount extends Account {
private SafeAccount() {
}
private SafeAccount(double amount) {
super(amount);
}
public static SafeAccount boo(double x) {
if (x < 0.0) {
return new SafeAccount();
}
return new SafeAccount(x);
}
}
在子类中使用private
构造函数来阻止构造函数的实例化并提供执行所需检查的工厂方法。
答案 1 :(得分:2)
您可以使用以下声明
@ECHO OFF
color 0b
title Display Selector by Nicholas Deckman
setlocal EnableExtensions EnableDelayedExpansion
CLS
echo -----------------------------------
echo Display Selector
echo by Nicholas Deckman
echo -----------------------------------
echo.
echo.
:Begin
ECHO 1.PC Display Only
ECHO 2.External Display Only
ECHO 3.Extend Display
ECHO 4.Duplicate
ECHO.
CHOICE /C 1234 /M "Enter the number of your choice:"
:: Note - list ERRORLEVELS in decreasing order
IF ERRORLEVEL 4 GOTO Duplicate
IF ERRORLEVEL 3 GOTO Extend
IF ERRORLEVEL 2 GOTO External
IF ERRORLEVEL 1 GOTO Internal
:Internal
echo.
ECHO Internal Display Selected
displayswitch.exe /internal
GOTO Confirm
:External
echo.
ECHO External Display Selected
displayswitch.exe /external
GOTO Confirm
:Extend
echo.
ECHO Extend Display Selected
displayswitch.exe /extend
GOTO Confirm
:Duplicate
echo.
ECHO Duplicate Display Selected
displayswitch.exe /clone
GOTO Confirm
:Confirm
echo.
CHOICE /T 15 /D N /M "Is this the setting you would like to keep? If no option is selected in 15 seconds, the display will revert to [PC ONLY] Display: "
IF ERRORLEVEL Y GOTO YES
IF ERRORLEVEL N GOTO NO
:NO
echo.
ECHO Reverting to [PC ONLY] Display
ECHO Reverted Success!
echo.
GOTO InternalBegin
:InternalBegin
echo.
ECHO Internal Display Selected
displayswitch.exe /internal
GOTO Begin
:YES
echo.
color 4
ECHO CMD FAIL
ECHO Thank you for using the Display Selector Tool by Nicholas Deckman
pause
GOTO End
:End
但总的来说,需要重新检查这种继承层次结构的正确性。