导入
1.同包下可以直接使用

2.不同包下要导入

3.导入java包
package one;
import java.util.Date;
public class Four {
public static void main(String[] args){
Date date = new Date();
System.out.println(date);
}
}
或
package one;
import java.util.*;
public class Four {
public static void main(String[] args){
Date date = new Date();
System.out.println(date);
}
}
三种访问指示符
0.前言
作用域 | 当前类 | 同一package | 子孙类 | 其他package |
---|---|---|---|---|
public | √ | √ | √ | √ |
protected | √ | √ | √ | × |
friendly(default) | √ | √ | × | × |
private | √ | × | × | × |
关于protected详细请去 第六章:类再生--->继承部分
1.public 可以在别的类中访问
package one;
public class Test {
public int a = 100;
public void sout(){
System.out.println("测试包");
}
}
package one;
public class Four {
public static void main(String[] args){
Test test = new Test();
test.sout();
System.out.println(test.a);
}
}
测试包
100
Process finished with exit code 0
2.private 只能在自己的类中访问 但是可以提供public函数让别的类中也可以访问
package one;
public class Test {
private int a = 100;
public int getA() {
return a;
}
}
package one;
public class Four {
public static void main(String[] args){
Test test = new Test();
System.out.println(test.getA());
}
}
100
Process finished with exit code 0
3.protected 自己和子类可以使用 别的类访问类似于private 通过public 函数访问
1>没有重复变量
package one;
public class ChildATest extends Test {
public int getSuperA(){
return super.a;
}
public int MyA(){
return a;
}
public void setA(int a){
this.a = a;
System.out.println(this.a);
System.out.println(super.a);
}
}
package one;
public class Four {
public static void main(String[] args) {
Test test = new Test();
System.out.println(test.getA());
ChildATest childATest = new ChildATest();
System.out.println(childATest.getSuperA());
System.out.println(childATest.MyA());
childATest.setA(100000);
}
}
100
100
100
100000
100000
Process finished with exit code 0
2>有重复变量
package one;
public class ChildATest extends Test {
private int a = 10;
public int getSuperA(){
return super.a;
}
public int MyA(){
return a;
}
public void setA(int a){
this.a = a;
System.out.println(this.a);
System.out.println(super.a);
}
}
package one;
public class Four {
public static void main(String[] args) {
Test test = new Test();
System.out.println(test.getA());
ChildATest childATest = new ChildATest();
System.out.println(childATest.getSuperA());
System.out.println(childATest.MyA());
childATest.setA(100000);
}
}
100
100
10
100000
100
Process finished with exit code 0
总结:
1.没有重复变量时 a, this.a, super.a 都指的是父亲的a
2.如果子类也定义了a, 那么只有super.a 指的是父亲的a, a, this.a 都是子类的a
网友评论