【问题标题】:Java how does child class use the variables which is in some function() of parent class?Java子类如何使用父类的某个函数()中的变量?
【发布时间】:2016-10-28 09:24:00
【问题描述】:

我写了一段代码如下:

class MyParent {
    String a = "abcdefg";
    String b;
    public void print() {
        b = "ABCDEFG";
        System.out.println(a);  
    }
}
class MyChild extends MyParent {
    String c = super.b;
    public void print2() {
        System.out.println(c);
    }
}

public class Parent {
    public static void main(String args[]) {
        MyParent mp = new MyParent();
        mp.print();
        MyChild mc = new MyChild();
        mc.print2();    
    }
}

有两个类,它们是父子类。 在 class MyParent 中声明了一个 b,并在函数 print() 中赋予了一个值。
我想在子类MyChild 中打印b。但是如果我运行代码,它可以正确打印,但b 显示null

我是 Java 新手。请帮帮我。


更新

感谢大家回答我的问题。我找到了解决方案。

我用了最简单的方法。我把它改成了**static String b**

static 让我的论点可以在各处使用。

但我不知道使用数据声明的确切方式。所以我会继续学习。

【问题讨论】:

标签: java class inheritance parent-child


【解决方案1】:

它打印null,因为在MyParent 类中您将其声明为空String。您在 print() 方法中初始化了 b。因此,如果您想获取 b 的值,您可以这样做:

MyChild mc = new MyChild();
mc.print();

【讨论】:

    【解决方案2】:

    mp 和 mc 对象的实例不同。所以对象 mp 中 b 的值设置为“ABCDEFG”,但 mc.b 仍然为空。

    尝试拨打mc.print(),然后拨打mc.print2()

    但是,如果您希望对象的不同实例在更新时共享相同的 b 值,则可以将 b 设为静态。

    【讨论】:

      【解决方案3】:

      你必须打电话

      print()
      

      MyParent 初始化"b"的方法。你没有初始化它。

      【讨论】:

        【解决方案4】:

        当你扩展类 evry 方法和属性时,如果父母得到了字符串 b,那么现在得到保护的更少的方法和属性转到孩子身上,孩子也得到了字符串 b 如果您希望孩子的字符串 b 与父字符串 b 的值相同,则您创建一个构造函数并在构造函数 this.b=super.b 中创建,以及创建对象时的含义子类的初始化属性。 现在在这段代码中你不应该像面向对象那样初始化属性。

            class MyParent {
                    String a = "abcdefg";
                    String b="ABCDEFG";
        
                    public MyParent(){}
        
                    public void print() {
                        System.out.println(a);  
                    }
                }
        
            class MyChild extends MyParent {
                public MyChild(){
                 this.b =super.b;
            }
                public void print2() {  
        
                  System.out.println(b); 
            }
        }
        
            public class Parent {
                public static void main(String args[]) {
                    MyParent mp = new MyParent();
                    mp.print();
                    MyChild mc = new MyChild();
                    mc.print2();    
                }
            }
        

        【讨论】:

          猜你喜欢
          • 2021-11-16
          • 1970-01-01
          • 1970-01-01
          • 2012-07-04
          • 2018-08-15
          • 2013-03-03
          • 1970-01-01
          • 2021-12-15
          相关资源
          最近更新 更多