java核心技术卷一(五)静态方法和非静态方法访问方式的区别及静态数据域和非静态数据域访问的区别

1.对于导入的包来说,调用静态方法应该有用 类名.方法名,调用非静态方法,应该用 类名.class.newInstance().方法名调用

2.使用类名.class.newInstance()真的会创建一个对象,如果该类有静态的id值,创建一个新对象增加这个值,那么通过这个方法创建的对象会增加这个id值。

3.一个类中可以有其他的类,其他类也可以和主类一样有main方法,常被用来做单元测试。

4.静态数据域又被称为是类域,所有类中的元素可以共享。那么静态方法就被称为是类方法,对象虽然也可以调用,但是不推荐。下面是实验的代码

package chapter4;

import java.time.LocalDate;
import chapter4.OtherClass;


public class TestStatic {

	public static void main(String[] args) throws InstantiationException, IllegalAccessException  {
		System.out.println(OtherClass.getnum());
		OtherClass.staticmethod();;
		OtherClass.class.newInstance().notstaticmethod();;
		System.out.println(OtherClass.getnum());
		myEmployee[] staff = new myEmployee[2];
		System.out.println();
		staff[0] = new myEmployee("duan ",LocalDate.now());
		staff[1] = new myEmployee("error!",LocalDate.now());
		System.out.println(staff[0].getid());
		System.out.println(staff[1].getid());
		System.out.println(myEmployee.getnextid());
	}
}

class myEmployee{
	private static int nextid=1;
	
	private String name;
	private LocalDate hire;
	private int id;
	
	myEmployee(){
		this.name = "noname";
		id = nextid;
		nextid++;
	}
	
	
	myEmployee(String name,LocalDate hire){
		this.name = name;
		this.hire = hire;
		id = nextid;
		nextid++;
	}
	
	public String getname(){
		return name;
	}
	
	public LocalDate getdate(){
		return hire;
	}
	
	public String toString(){
		return "I am " + getname() + hire;
	}
	public int getid(){
		return id;
	}
	public static int getnextid(){
		return nextid;
	}
	
	public static void main(String args[]){
		for(int i=0;i<10;i++){
			new myEmployee();
		}
		if(myEmployee.getnextid() == 11)
			System.out.println("true!");
		else
			System.out.println("false!");
	}
}
package chapter4;

public class OtherClass {
	private static int num=1;
	
	public OtherClass(){
		num++;
	}

	public static void main(String[] args) {
		System.out.println("this is main");
	}
	public static void staticmethod(){
		System.out.println("this is static method");
	}
	public void notstaticmethod(){
		System.out.println("this not static method!");
	}
	public static int getnum(){
		return num;
	}
}

结果如下

1
this is static method
this not static method!
2

1
2
3
我么可以看到OtherClass的num确实增加了,另外从代码中也可以看出访问不同的方法采用的形式。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值