我还在学习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
}
实例方法指必须创建类的对象才能访问该方法。另一方面,对于静态方法,由于它是类的属性而不是其对象/实例的属性,因此可以在不创建类的任何实例的情况下访问它。但请记住,静态方法只能访问静态变量,而实例方法可以访问类的实例变量。
静态方法和静态变量对于内存管理非常有用,因为它不需要声明对象,否则会占用内存。
实例方法和变量的示例:
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.
}
实例方法是需要对象才能访问的方法,而静态方法则不需要。您提到的方法是一个实例方法,因为它不包含 static 关键字。
实例方法的示例:
class main
{
public void instanceMethod()//instance method
{
System.out.println("Hello world");
}
}
main obj=new main();//instance of class "main"
obj.instanceMethod();//accessing instance method using object