class Person{
String name ;
int age ;
public Person(String n,int a){ // 声明构造方法,为类中的属性初始化
name=n ;
age=a ;
}
public void tell(){
System.out.println("姓名:" + name + ";年龄:" + age) ;
}
};
public class ConsDemo02{
public static void main(String args[]){
System.out.println("声明对象:Person per = null ;") ;
Person per = null ; // 声明对象时并不去调用构造方法
System.out.println("实例化对象:per = new Person() ;") ;
per = new Person("张三",30) ;//实例化对象
per.tell() ;
}
};
问题:
例如这个例子中主方法中调用的tell方法就不是static的,是不是别的类中的方法不要求一定是static?
新人请教,多谢各位:)
String name ;
int age ;
public Person(String n,int a){ // 声明构造方法,为类中的属性初始化
name=n ;
age=a ;
}
public void tell(){
System.out.println("姓名:" + name + ";年龄:" + age) ;
}
};
public class ConsDemo02{
public static void main(String args[]){
System.out.println("声明对象:Person per = null ;") ;
Person per = null ; // 声明对象时并不去调用构造方法
System.out.println("实例化对象:per = new Person() ;") ;
per = new Person("张三",30) ;//实例化对象
per.tell() ;
}
};
问题:
例如这个例子中主方法中调用的tell方法就不是static的,是不是别的类中的方法不要求一定是static?
新人请教,多谢各位:)
static定义的方法是静态方法,通过类来访问,比如Person.XXXX()
其它方法只能通过实例来访问,比如per.XXXX()
所以你能通过per.tell()来调用tell,因为per是一个实例。
但你不能通过Person.tell()来调用,因为tell不是static方法。
对于本类的方法
ConsDemo02.xxx()可以调用static方法,如果在本类的main()内调用,由于是本类,可以省略写成xxx()
如果xxx不是静态方法的话,可以如下调用:
ConsDemo02 cd = new ConsDemo02();
cd.xxx();
其它方法只能通过实例来访问,先创建实例: Person per = new Person("lz",22),然后通过per.tell()调用。
1.如果你在person定义了static的方法,那么你在外类中可以直接使用person.XXX()方法进行操作
2.如果不是static方法,就要进行实例化出person对象进行操作一般情况下定义static方法都是一些常量、或者是一些通用方法
A类有两个方法one和two 其中方法one是static修饰
那你在B类中可以直接用A.one()来调用方法而不必直接实例出A
而调用two方法就必须要 new出一个实例a 然后通过a.two来调用