标准本的类
package org.example.classTest;
// 一个标准类
class Car{
private String brand;
public Car(String brand){
this.brand = brand;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
}
public class StandardClassTest {
public static void main(String[] args) {
Car jili = new Car("吉利");
System.out.println(jili.getBrand());
}
}
内部类:如果一个类定义在另一个内的内部,这个类就是内部类
场景:当一个类的内部,包含了一个完整的事物,且这个事物没必要单独设计时,就可以把这个事物设计成内部类。
成员内部类
成员内部类案例:
package org.example.classTest;
class Outer{
int number = 10;
public void show(){
System.out.println(number);
}
public class Inner {
int number = 20;
public void show(){
System.out.println(number);
}
}
}
public class InnerClassTest {
public static void main(String[] args) {
Outer outer = new Outer();
outer.show();
// 成员内部类的实例化 外部类名.内部类名 对象名 = new外 部类名.内部类名().new 内部类名()
Outer.Inner inner = new Outer().new Inner();
inner.show();
}
}
静态内部类
有static 修饰的内部类
package org.example.classTest;
class Outer2{
static class Inner{
int num = 10;
public void show(){
System.out.println(num);
}
}
}
public class StaticInnerClassTest {
public static void main(String[] args) {
// 外部类名.内部类名 对象名 = new 外部类名.内部类名()
Outer2.Inner inner = new Outer2.Inner();
inner.show();
}
}
局部内部类
局部类内部类是定义在类的方法中、代码块中,构造器中的类;这是一种鸡肋写法,实际代码一般不这么写。
package org.example.classTest;
class Outer3{
public void test(){
// 局部类
class A{
}
}
// 局部抽象类
abstract class B{
}
// 局部接口
interface C{
}
}
public class PartInnerClassTest {
public static void main(String[] args) {
}
}
匿名内部类(重点)
匿名内部类就是一种特殊的局部内部类,所谓匿名,指的是程序员不需要为这个类声明名字。
package org.example.classTest;
public class AnonymousInnerClassTest {
public static void main(String[] args) {
showArts(new Arts() {
@Override
public void sing() {
System.out.println("唱歌");
}
});
}
public static void showArts(Arts art){
art.sing();
}
}
interface Arts{
public void sing();
}