如何在外部调用被封装的属性:
在封装属性的类 内部定义一个 方法接收封装属性,然后再外部调用此方法,即可调用被封装的属性。
static关键字:
◉static方法不能直接访问非static属性或方法,只能调用static属性或方法;
◉非static方法可以访问static的属性或方法,不受任何限制。
static修饰的变量和方法无需实例化直接访问,而不用static修饰的变量和方法只能通过对象名访问
代码块:
由{}定义一段语句,根据此部分定义的位置以及声明的关键字的不同,一共分为4种:普通代码块、构造块、静态块、同步代码块。
普通代码块:写在方法里的代码块。(定义的普通代码块中的属性是局部变量)
public class Test2{
public static void main(String args []){
{int num = 10;
System.out.println("代码块局部变量"+num);
}
int num = 100;
System.out.println("全局变量"+num);
}
}
//代码块局部变量10
全局变量100
构造块:写在类里面的代码块。(代码的结构与顺序无关,构造块在每一次实例化类对象时都会被调用,而且优与构造方法执行)
class Book11{
public Book11(){
System.out.println("[A]Book类的构造方法");
}
{
System.out.println("[B]Book类的构造块");
}
}
public class Test3{
public static void main(String args []){
new Book11();
new Book11();
}
}
//[B]Book类的构造块
[A]Book类的构造方法
[B]Book类的构造块
[A]Book类的构造方法
静态块:使用static定义的代码块。(静态块会优先调用,而且只调用一次)
class Book11{
public Book11(){
System.out.println("[A]Book类的构造方法");
}
{
System.out.println("[B]Book类的构造块");
}
static{
System.out.println("[C]Book类的构造块");
}
}
public class Test4{
public static void main(String args []){
new Book11();
new Book11();
}
}
//[C]Book类的构造块
[B]Book类的构造块
[A]Book类的构造方法
[B]Book类的构造块
[A]Book类的构造方法
JDK1.7之前的BUG:静态块会优先于主方法执行。
内部类:
作用:轻松地访问外部类中的私有属性。(外部类也可以通过内部类对象轻松地访问内部类的私有属性)
内部类的class文件的形式:Outer$Inner.class
内部类对象实例化:Outer.Inner in = new Outer().new Inner();
class Outer{ //外部类
private String msg = "Hello World";
class Inner{ //内部类
private String msg2 ="全世界失眠"; //内部类私有属性
public void print(){
System.out.println(msg); //直接访问外部类的私有属性
}
}
public void fun(){
Inner in = new Inner(); //内部类对象
System.out.println(in.msg2); //直接利用内部类对象访问内部类中的私有属性
}
}
public class Test2{
public static void main(String args[]){
Outer out = new Outer(); //实例化外部类对象
Outer.Inner in = new Outer().new Inner(); //实例化内部类对象
out.fun(); //调用外部类的方法
in.print(); //调用内部类的方法
}
}
输出结果:全世界失眠
Hello World
私有内部类:一个内部类只能被一个外部类调用,不能被外部调用。(给内部类加上private即可)
使用static定义内部类:
class Outer{
private static String msg = "Hello World!";
static class Inner {
public void print(){
System.out.println(Outer.msg);
}
}
}
public class Test3 {
public static void main(String[] args) {
Outer.Inner in = new Outer.Inner();
in.print();
}
}
static 定义的内部类等同于外部类。
实例化内部类的格式比较:
1.无static | 2.有static |
---|---|
Outer.Inner in = new Outer().new Inner(); | Outer.Inner in = new Outer.Inner(); |
在方法中定义内部类:
class Outer{
private static String msg = "Hello World!";
public void fun(){
class Inner{
public void print(){
System.out.println(Outer.this.msg);
}
}
new Inner().print(); //内部类实例化对象调用print()输出
}
}
public class Test3 {
public static void main(String[] args) {
Outer out = new Outer();
out.fun();
}
}