在 Java 中实例化一个对象

在 Java 中实例化一个对象

在 Java 中,对象被称为类的实例。例如,让我们假设一个名为 car 的类,那么 SportsCar、SedanCar、StationWagon 等都可以被认为是这个类的对象。

在本教程中,我们将讨论如何在 Java 中实例化对象。

使用 new 关键字,我们可以在 Java 中创建类的实例。请记住,我们不会在 Java 中实例化方法,因为对象是类的实例而不是方法。方法只是类拥有的一种行为。

通过创建一个类的对象,我们可以通过另一个类访问它的公共方法。就像下面的代码一样,我们在第一个类中创建第二个类的实例,然后在第一个类中使用第二个类的方法。

// creating a class named first

public class First {

public static void main(String[] args) {

Second myTest = new Second(1, 2); // instantiating an object of class second

int sum = myTest.sum(); // using the method sum from class second

System.out.println(sum);

}

}

// creating a class named second

class Second {

int a;

int b;

Second(int a, int b) {

this.a = a;

this.b = b;

}

public int sum() {

return a + b;

}

}

输出:

3

如果我们希望从同一个类的另一个方法中访问一个类的方法,如果该方法被声明为 static,则没有必要实例化一个对象。

例如,

public class Testing {

private static int sample(int a, int b) {

return a + b;

}

public static void main(String[] args) {

int c = sample(1, 2); // method called

System.out.println(c);

}

}

输出:

3

在上面的示例中,我们可以调用方法 sample(),因为这两个方法属于同一类,并且 sample() 被声明为 static,因此不需要对象。

但是如果两个方法属于同一个类,我们仍然可以执行对象实例化,如下所示。如果该方法未声明为 static,则完成。

请参考下面的代码。

public class Testing {

private int Sample() {

int a = 1;

int b = 2;

int c = a + b;

return c;

}

public static void main(String[] args) {

Testing myTest = new Testing();

int result = myTest.Sample();

System.out.println(result);

}

}

输出:

3

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

相关推荐

吸食笑气成瘾怎么办?如何戒掉笑气?
beat365体育亚洲版

吸食笑气成瘾怎么办?如何戒掉笑气?

📅 09-07 👁️ 7744
Win10玩CF全屏设置终极指南:告别黑边,畅享沉浸式射击体验!
955路 Route: Schedules, Stops & Maps
365bet下注

955路 Route: Schedules, Stops & Maps

📅 08-04 👁️ 5123