实例方法的示例? (JAVA)

我还在学习Java中的方法,并且想知道你如何使用实例方法。 我在考虑这样的事情:

public void example(String random) { } 

但是,我不确定这实际上是实例方法还是其他类型的方法。 有人可以帮帮我吗?

如果它不是静态方法,那么它就是一个实例方法。 这是一个或另一个。 是的,你的方法,

 public void example(String random) { // this doesn't appear to do anything } 

是一个实例方法的示例。

关于

并且想知道你究竟如何使用实例方法

您将创建该类的实例,一个对象,然后在该实例上调用实例方法。 即

 public class Foo { public void bar() { System.out.println("I'm an instance method"); } } 

可以使用如下:

 Foo foo = new Foo(); // create an instance foo.bar(); // call method on it 
 class InstanceMethod { public static void main(String [] args){ InstanceMethod obj = new InstanceMethod();// because that method we wrote is instance we will write an object to call it System.out.println(obj.sum(3,2)); } int f; public double sum(int x,int y){// this method is instance method because we dont write static f = x+y; return f; } } 

* 实例方法*是与对象关联的方法,每个实例方法都使用引用当前对象的隐藏参数进行调用。 例如,在实例方法上:

 public void myMethod { // to do when call code } 

实例变量名称对象具有作为实例变量实现的属性,并在其生命周期内随其携带。 在对象上调用方法之前存在实例变量,而方法正在执行,并且在方法完成执行之后。 类通常包含一个或多个方法来操作属于该类的特定对象的实例变量。 实例变量在类声明中声明,但在类的方法声明的主体之外。 该类的每个对象(实例)都有自己的每个类的实例变量的副本。

实例方法意味着必须创建类的对象才能访问该方法。 另一方面,对于静态方法,作为Class的属性而不是其对象/实例的属性,可以在不创建类的任何实例的情况下访问它。 但请记住,静态方法只能访问静态变量,而实例方法可以访问类的实例变量。 静态方法和静态变量对于内存管理很有用,因为它不需要声明否则会占用内存的对象。

实例方法和变量的示例:

 public class Example { int a = 10; // instance variable private static int b = 10; // static variable (belongs to the class) public void instanceMethod(){ a =a + 10; } public static void staticMethod(){ b = b + 10; } } void main(){ Example exmp = new Example(); exmp.instanceMethod(); // right exmp.staticMethod(); // wrong..error.. // from here static variable and method cant be accessed. }