java - 如何使用另一个类的私有变量打印默认构造函数
问题描述
我想打印默认的 private并且bloodtype
我想从另一个具有 main 方法的类中打印它。 rhfactor
O+
+
我已经尝试创建新对象并打印它们,但它仍然说我正在访问一个私有变量。当您在上面输入内容时,scanner
它会打印它,但如果您不输入任何内容,我想用私有变量打印构造函数!
public class blooddata {
private String bloodtype;
private String rhFactor;
blooddata(){
bloodtype = "O";
rhFactor = "+";
}
blooddata(String btx, String rhx){
this.bloodtype = btx;
this.rhFactor = rhx;
}
public String getblood (String bloodtype){
return bloodtype;
}
public String getfactor (String rhFactor){
return rhFactor;
}
public void setblood(String bloodtype){
this.bloodtype = bloodtype;
}
public void setfactor(String factor){
this.rhFactor = factor;
}
}
这是具有主要方法的类
import java.util.Scanner;
public class Runblooddata {
static Scanner sc = new Scanner(System.in);
static String btx;
static String rhx;
public static void main(String[] args) {
System.out.print("Enter blood type: ");
btx = sc.nextLine();
System.out.print("Enter rhFactor: ");
rhx = sc.nextLine();
if (btx.isEmpty() || rhx.isEmpty()){
blooddata asd = new blooddata(); //this is where i am lost
}else{
blooddata bd = new blooddata();
bd.setblood(btx);
bd.setfactor(rhx);
System.out.println(bd.getblood(btx));
System.out.println(bd.getfactor(rhx));
}
}
}
解决方案
吸气剂不应该有参数。
当您声明与字段同名的方法参数时,该参数会隐藏该字段。您基本上返回您采用的参数。
6.4.1. 阴影
一个名为 n 的字段或形式参数的声明 d 在 d 的整个范围内隐藏了在 d 出现点的范围内的任何其他名为 n 的变量的声明。
public String getBlood() {
return bloodtype;
}
public String getFactor() {
return rhFactor;
}
我会帮你简化一下。
final class Example {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter blood type: ");
String btx = sc.nextLine();
System.out.print("Enter rhFactor: ");
String rhx = sc.nextLine();
BloodData data = btx.isEmpty() || rhx.isEmpty() ?
new BloodData() :
new BloodData(btx, rhx);
System.out.println(data.getBloodType());
System.out.println(data.getRhFactor());
}
}
final class BloodData {
private final String bloodType;
private final String rhFactor;
BloodData() {
this("O", "+");
}
public BloodData(String bloodType, String rhFactor) {
this.bloodType = bloodType;
this.rhFactor = rhFactor;
}
public String getBloodType() {
return bloodType;
}
public String getRhFactor() {
return rhFactor;
}
}
推荐阅读
- eclipse - 我必须在我的 Eclipse Web 项目中更改什么配置,以便 Tomcat 重定向 URL,而不需要任何指向项目 URL 的路径
- flutter - 收到错误“ParentDataWidget 使用不正确”。扑通扑通
- c# - 在我的嵌套 if 语句中我做错了什么吗?
- tabulator - 如何突出显示最大或最小数据?
- agda - 阿格达商店 Comonad
- python - curl --cacert vs python请求验证
- flutter - 在 Flutter 中保留状态的引用是否安全?
- c - Boehm GC 是否将 Win32 Fibers 堆栈识别为根?
- reactjs - 为什么蚂蚁设计抽屉不显示关闭图标?
- python - 构建节点链?