从android中的另一个类访问一个类

时间:2014-01-28 10:24:24

标签: android this

如果我们需要从另一个类访问一个类,我们创建该类的一个对象 - 但为什么我们在括号中使用this关键字,而在java中不需要这个? 有人可以帮忙吗?

public class SQLView extends Activity
{ 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        // TODO Auto-generated method stub 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.sqlview); 
        TextView tv=(TextView) findViewById(R.id.tvSQLinfo); 
        HotOrNot info=new HotOrNot(this); 
        info.open(); String data=info.getData(); 
        info.close(); tv.setText(data); 
    }
}

2 个答案:

答案 0 :(得分:1)

this总是指当前班级的对象。

如果在父类和子类中有两个具有相同名称的方法,并且您想要访问子类的方法,那么您需要使用this.methodName()来表示您要访问子类& #39;方法。

例如

public class parentClass 
{ 
    public void printMsg()
    {
         System.out.println ( "This is Parent Class" );
    } 
}


public class childClass extends parentClass
{
     public void printMsg()
     {
         System.out.println ( "This is child class" );
     } 

     public static void main ( String args[] )
     {
         ChildClass cc = new ChildClass(); 
         cc.printMsg();   // This will print Parent class's printMsg() method
         this.printMsg();   // This will print child class's printMsg() method

     } 
}

答案 1 :(得分:0)

this”指当前的类对象。除此之外,您还可以使用getApplicationContext()。或者你也可以这样做:

public class MainActivity extends Activity
{
  Context context=this;
  public void onCreate(...)
  {
    // when you would like to accessing one class from present class then you can also use "context"
  }
}