java中类的分类

java中类的分类

标准本的类

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();

}

相关推荐

全球地址搜索工具
365bet365打不开

全球地址搜索工具

📅 06-28 👁️ 6821
交通事故报案后多久会自动销案
365平台是做什么的

交通事故报案后多久会自动销案

📅 06-29 👁️ 9563
搜狗输入法怎么使用细胞词库?使用细胞词库的方法
365BET娱乐场下载

搜狗输入法怎么使用细胞词库?使用细胞词库的方法

📅 07-02 👁️ 2461
挥的解释
365平台是做什么的

挥的解释

📅 06-29 👁️ 4868
win11电脑安装包怎么删除?如何彻底清除?
365bet365打不开

win11电脑安装包怎么删除?如何彻底清除?

📅 07-02 👁️ 5659
怎么样能让兔子奶水多?
365BET娱乐场下载

怎么样能让兔子奶水多?

📅 07-01 👁️ 3776
自定的铃声文件该存在哪个文件夹
365BET娱乐场下载

自定的铃声文件该存在哪个文件夹

📅 06-27 👁️ 2178
横行霸道图奇
365BET娱乐场下载

横行霸道图奇

📅 07-01 👁️ 7571
w10投影全屏设置
365平台是做什么的

w10投影全屏设置

📅 06-29 👁️ 7930