在android中创建对象

时间:2019-04-08 05:26:09

标签: java android

我在android studio上创建类的对象时遇到问题。我创建了一些名为Fan,Light和Device的类。

当我尝试在MainActivity.java中实例化Fan and Light时,出现以下错误:

  • 从未使用字段'myFan'

  • 无法解析符号'breakDevice'

代码如下所示。感谢您解决此问题。 谢谢

  

MainActivity.java

public class MainActivity extends Activity 
{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public Light myLight = new Light();

    Fan myFan = new Fan();

    myFan.breakDevice();
    myLight.breakDevice();
}
  

Fan.java

package com.example.codealong3;

import android.util.Log;

public class Fan extends Device{

    public Fan() {
        setDeviceName("FAN");
    }

    @Override
    public void breakDevice() {
        Log.e(getDeviceName(), "BANG ! It's broken");
    }
}
  

Light.java

package com.example.codealong3;

import android.util.Log;

public class Light extends Device {

    public Light() {
        setDeviceName("LIGHT");
    }

    @Override
    public void breakDevice() {
        Log.e(getDeviceName(), "Glass Everywhere! .. I guess that's not bad");
    }
}

3 个答案:

答案 0 :(得分:0)

您已经将对象创建为精细字段。

但是,您不能在任何其他方法之外调用实例方法,因此必须在onCreate内使用中断设备,或者作为按钮单击事件的一部分,例如

答案 1 :(得分:0)

尝试

  

MainActivity.java

 public class MainActivity extends Activity 
    {

        public Light myLight = new Light();

        Fan myFan = new Fan();

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            myFan.breakDevice();

            myLight.breakDevice();  
      }    

    }

答案 2 :(得分:0)

实例化是正确的,但是您只能在方法内部访问对象的方法,而不能在类级别访问

您可以在A Maharaja或其他方法采样的onCreate方法中访问它。

public class MainActivity extends Activity 
{
    //Instantiate object on global or class level
    public Light myLight = new Light();
    Fan myFan = new Fan();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        executeObjectCommands();
    }

    //You can execute your commands inside this method
    //You can also separate them in different methods and return something if needed
    public void executeObjectCommands()
    {
        myFan.breakDevice();
        myLight.breakDevice();
    }
}