2011-10-29 122 views
1

我想从另一个类调用一个方法,并从我收集的方法中,我试图调用的方法是一个实例方法。我收集到了这一点,这意味着它使用对象的实例变量。有没有简单的方法来调用这个方法?非静态方法不能从静态上下文中引用

这是最主要的方法,

public void main() 
{ 
    Test.testPetOwner(); 
} 

这是我想在一个名为“测试”

public void testPetOwner() 
{ 
    String petName; 
    String species; 
    String hairCondition; 
    String posture; 

    testCompetitor(); 

    PetOwner petOwner1 = new PetOwner(); 

    System.out.println("What is the pet's name?"); 
    petName = Genio.getString(); 
    petOwner1.setPetName(petName); 

    System.out.println("What is the species of the pet?"); 
    species = Genio.getString(); 
    petOwner1.setSpecies(species); 

    System.out.println("What is the hair condition of the pet?"); 
    hairCondition = Genio.getString(); 
    petOwner1.setHairCondition(hairCondition); 

    System.out.println("How is the pet's posture?"); 
    posture = Genio.getString(); 
    petOwner1.setPosture(posture); 
} 

回答

1
public void main() 
{ 
    Test t = new Test(); 
    t.testPetOwner(); 
} 
+0

非常感谢!当你看到答案时,它总是显而易见的! – Struan

0

如果我们试图访问类调用该方法一个来自静态上下文的实例方法,编译器现在可以猜测出您正在引用哪个实例方法(哪个对象的变量)。尽管您始终可以使用对象引用来访问它。

相关问题