在Java中,如果不是Main(),我什么时候可以访问此实例



所以我试图为学习目的制作一个简单的摇摆应用程序,我对此有些困惑。我了解程序的入口点是main()函数,并且该对象当时不存在,因此我无法使用this来指代,但是我如何以及何时知道创建了实例?

我的类扩展了JFrame,因此执行时已经具有视觉存在,并且在创建它后,我想将其定位在屏幕上的特定位置上。但是唯一的选择似乎是使用new ClassName(),但这将创建第二个实例。...所以,我是一个总体初学者,并且很困惑

您只需要在主要中创建类的实例:

MyClass c = new MyClass("A nice frame title here");

然后在您的类构造函数或方法中:

public MyClass(String title) {
   //you can use this here
}
public void method() {
   //and here
}

您必须自己明确创建实例。例如,

class MyJavaClass{
    public static void main(String args[]){
        MyJavaClass myJavaClass = new MyJavaClass();
    }
}

在您开始使用Swing进行GUI开发之前,最好学习Java的基础知识,面向对象的编程和实例化。

Java设计为面向对象的语言例如

    public class Animal{ //this is a super class
    private String name;
    public String getName(){
     return name;
    }
    public void setName(String name){
     this.name = name;
    }
    }
    public class Dog extends Animal{/*this is a subclass that inherits from Animal namely the name attribute, the getName and setName(String n) function.*/
    public Dog(String n){/*this is a constructor function/method, while classes would have a constructor method, you can create other constructor methods to accept parameters/required values */
     this.name = n;/*this name is equal to the String value inputted on instantiation.
if you happen to set a name inside the superclass (Animal) and want to use that, you can remove the String n from the constructor's parentensis and simply use super.getName(); instead of this.name;*/
    }
    }

    public class MainClass{
        public static void main(String args[]){
         Dog germanShepard = new Dog("Sir Isaac Woofington"); /*<-this is making an instance of a Dog.*/
        System.out.println(germanShepard.getName()); //this is printing out the name of the dog
    }
    }

进一步添加了主要功能。

public static void main(Strings args[]){
}

必须成功编译应用程序,当您击中编译器时,编译器将寻找此方法,如果找不到它不会做任何事情。此外,进一步是运行代码其余部分的切入点以狗为例以下是处理的顺序:编译

 Search for main method
found main method
sequentially go through the main method line by line 
Create an instance of dog called germanShepard
step into dog class 
dog class inherits Animal behaviour
set the dogs name to the property inherited from Animal
step out of class

通过访问与狗的方法打印内容,称为getName();

最新更新