导入(import)那点事

来源:互联网 发布:蚁群算法优化问题 编辑:程序博客网 时间:2024/06/05 06:11

1、导入,关键词 import

答:import导入的是命名空间,这样你就可以访问其它package下的文件了。(前提是访问权限已经许可)


2、在java文件中,我们经常看到import,本条是导入包里一个文件的情况

答:import 全称,这样我们就可以任意使用这个导入的名称,不然你还要每次都输入全称啊?例如Activity,你import后,就简单了,直接像下面那样开搞

public class Snake extends Activity {}

如果不做import呢?就会是下面这样,得输入Activity的全称,妈啊,抓狂不?

public class Snake extends android.app.Activity {}

/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package com.example.android.snake;import android.app.Activity; //import 类全称; import android.os.Bundle;import android.util.Log;import android.view.KeyEvent;import android.view.MotionEvent;import android.view.View;import android.view.View.OnTouchListener;import android.widget.TextView;

3、导入一个包下所有的文件,下面这个例子就是,我就用的Android的framework作例子了!,这样这个包下面所有的文件,你都能使用(前提当然是访问权限许可下)

import android.app.*;  //导入android.app下所有的文件,*代指文件

4、后来java大神又加入了静态导入,可以单独导入一个类的静态方法,或者导入它的全部静态方法,这样调用静态方法的时候,前面连类名都不用加,仿佛就像是自己的静态方法一样,确实牛逼!!!语法:import static 

package com.test.a;import static org.junit.Assert.assertNotNull; //这里用了import static 语法class TimeTest {public static void main(String args[]) {assertNotNull("temp"); //好处在这里,assertNotNull作为静态方法,这时我调用它可以连类名都不用加}}

5、静态导入一个类的全部静态方法,幸福满满的

import static org.junit.Assert.*;



0 0