`
Rainbow702
  • 浏览: 1073270 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类

新建对象的疑问

    博客分类:
  • Java
阅读更多

对于Java中新建一个对象,大家可能再熟悉不过了,如:

public class Person {

	private String name;

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public String aaa() {
		return "AAA";
	}

	public static void main(String[] args) {
		Person p = new Person();
		p.setName("123");
		System.out.println(p.getName());
	}
}

 上面的main方法中的 新建对象方式,对于每个Javaer来说,都不应该有任何疑问。

但是,今天在看Struts2源码时,遇到了以下的代码:

protected List<String> extensions = new ArrayList<String>() {{
        add("action");
        add("");
    }};

 一开始还楞了一下,怀疑这代码能运行么?

因为这跟我以前声明list的方式不一样,相比之前,我们一般都是如下来声明并初始化list的:

protected List<String> extensions = new ArrayList<String>();
extensions.add("action");
extensions.add("");

 

然后我就脑洞开了一下,既然List可以这么来写,那么其他类是不是也可以这么搞呢?

就拿本文开头的Person类来举例吧,我发现如下这样声明也是可以的:

public class Person {

	private String name;

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public String aaa() {
		return "AAA";
	}

	public static void main(String[] args) {
		Person p = new Person() {
			{
				setName("123");

			}

			public String aaa() {
				return "aaa";
			}

			public String bbb() {
				return "bbb";
			}
		};

		System.out.println(p.name);
		System.out.println(p.aaa());
	}
}

 这样看起来感觉 很怪,但是它是可以运行的,而且它的运行结果是:

123
aaa

也就是 Person类中定义的aaa()方法被 p 实例中的aaa()给覆盖了。

 

现象比较好玩,但是不知道这是什么语法,还请有识者指点一下。

 

////////////////////////////////////分隔线(2015年10月27日)////////////////////////////////////////////////////

今天无意在 Oracle官方网站上学习 Nested Class 相关语法时,找到了解答:

http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

 

■ Syntax of Anonymous Classes

As mentioned previously, an anonymous class is an expression. The syntax of an anonymous class expression is like the invocation of a constructor, except that there is a class definition contained in a block of code.

The anonymous class expression consists of the following:

● the new operator

● The name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface HelloWorld.

● Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.

● A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.


■ Accessing Local Variables of the Enclosing Scope, and Declaring and Accessing Members of the Anonymous Class

Like local classes, anonymous classes can capture variables; they have the same access to local variables of the enclosing scope:

● An anonymous class has access to the members of its enclosing class.

● An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.

● Like a nested class, a declaration of a type (such as a variable) in an anonymous class shadows any other declarations in the enclosing scope that have the same name. See Shadowing for more information.

Anonymous classes also have the same restrictions as local classes with respect to their members:

● You cannot declare static initializers or member interfaces in an anonymous class.

● An anonymous class can have static members provided that they are constant variables.

Note that you can declare the following in anonymous classes:

● Fields

● Extra methods (even if they do not implement any methods of the supertype)

● Instance initializers

● Local classes

However, you cannot declare constructors in an anonymous class.

 

 

从上面的解释来看:

其实,我上面的写法,就相当于声明了一个匿名类,这个匿名类是 Person 类的一个子类(但是没有显示进行定义)。另外,虽然在这个 匿名类 中增加了一个 bbb() 方法,但是因为 Person 类中并没有 bbb()这个方法,而且 p 变量又是 Person 类的一个实例,所以无法通过 p 变量去调用 bbb() 方法。

分享到:
评论

相关推荐

    第十课 对象进阶1

    #### 二、新建对象实例 创建对象实例的过程是JavaScript编程中非常基础且常用的操作。下面我们将详细介绍如何通过不同的方式创建这些实例。 ##### 2.1 使用 `new` 关键字创建对象 最常见的方式是使用`new`关键字...

    新建MicrosoftOfficePowerPoint演示文稿 (4).pptx

    )"each"作为主语时,通常与单数动词搭配,即使它指代的是多个对象。 - "Each of them has a capital."(他们每个人都有一个首都。)同样,"each of + 定冠词 + 复数名词"结构中的动词也是单数形式。 在制作...

    autocad绘图常见疑难解答

    疑问:为什么利用夹点镜像图形对象,源对象总不能保留? 答疑:默认情况下,镜像命令会删除源对象。若需保留原对象,可在执行命令前选择“复制”选项。 #### 十四、BHATCH与HATCH命令区别 疑问:BHATCH命令与...

    Illustrator快捷键-高手之路.pdf

    用户在实际应用时,应根据Illustrator的实际操作环境,对有疑问的快捷键进行测试验证,以确保快捷键的功能准确性。此外,某些快捷键可能在不同的系统或软件版本中具有不同的功能,用户应以实际软件为准。

    CAD2004快捷键大全.pdf

    1. F1:获取帮助 - 在遇到操作疑问时,按F1可以快速访问CAD的帮助系统。 2. F2:切换窗口 - 在绘图窗口和文本窗口之间进行快速切换。 3. F3:对象捕捉 - 开启或关闭对象捕捉功能,用于精确对齐和定位图形元素。 4...

    FLASH最常用快捷键.docx

    - **Ctrl+F8**:直接新建元件,无需先选择对象。 - **Ctrl+B**:打散组合的对象,使其变为可编辑的原始形状。 - **Ctrl+G (修改—组合)**:组合多个对象为一个整体。 - **Ctrl + shift + G**:取消组合。 - **...

    PowerPCB快捷指令

    1. **新建设计**:`Ctrl+N`,这个快捷键用于创建新的电路板设计项目。 2. **打开设计**:`Ctrl+O`,快速打开已有的设计文件。 3. **保存设计**:`Ctrl+S`,及时保存设计避免意外丢失。 4. **复制对象**:`Ctrl+C`,...

    中望CAD快捷键汇总.doc

    - `CTRL+N` 或 `N`: 新建文件,开始新的设计。 - `CTRL+O`: 打开已有的CAD文件。 - `CTRL+P`: 打印设计稿,进行预览和输出。 - `CTRL+Q` 或 `ALT+F4`: 退出中望CAD程序。 - `CTRL+S` 或 `SA`: 保存当前文件,...

    CAD2016快捷键命令大全快捷键技巧.docx

    - `CTRL+M`:调出帮助菜单,解答操作疑问。 - `CTRL+N`:新建一个新的绘图文件。 - `CTRL+O`:打开已有的绘图文件。 - `CTRL+P`:打印图纸,预览并输出到打印机。 - `CTRL+Q`:退出CAD程序。 - `CTRL+S`:保存...

    AutoCAD快捷键大全和特殊字符输入[汇编].pdf

    - F1: 获取帮助 —— 当遇到操作疑问时,可以快速打开帮助文档。 - F2: 切换文本窗口 —— 在绘图窗口和文本编辑窗口之间快速切换。 - F3: 对象自动捕捉 —— 开启或关闭对象捕捉功能,用于精确对齐图形元素。 - F4:...

    CAD快捷键的使用

    28. 寻求帮助:F1,访问CAD的帮助文档,解决操作疑问。 29. 正交模式:F3,开启或关闭正交模式,确保直线垂直或水平绘制。 30. 对象捕捉:F3,打开或关闭对象捕捉,精确捕捉图形的特定点。 31. 直线标注:DLI+空格,...

    2021-2022计算机二级等级考试试题及答案No.13292.docx

    2. **Windows98帮助功能**:Windows98操作系统提供了"帮助"菜单项,用户可以通过此功能获取操作指南和解决疑问。 3. **Java类的继承**:Java语言支持单重继承,即一个类只能继承一个父类,选项B正确,其他选项错误...

    labview快捷方式

    1. `CTEL+N`:新建文件 - 创建一个新的VI(虚拟仪器)或函数面板。 2. `CTEL+=`:字体放大 - 增大选中文本或对象的字体大小。 3. `CTEL+E`:切换程序框图 - 在前面板和程序框图之间切换,这对于查看和编辑代码非常...

    AutoCAD快捷键

    在使用过程中遇到任何疑问时,可以按下此键来查询相关的帮助文档。 - **F2**:切换绘图窗口与文本窗口。这对于需要查看命令历史或输入长文本的用户非常有用。 - **F3**:启用/禁用对象捕捉模式。这是一种非常重要的...

    天正建筑常用快捷键.doc

    - `Ctrl` + `N`、`M`: 新建文件,开始新的设计。 - `Ctrl` + `P`: 打印文件,输出图纸。 - `Ctrl` + `S`: 保存文件,防止数据丢失。 - `Ctrl` + `Z`: 撤销操作,回退至上一步。 - `Ctrl` + `X`: 剪切选定的对象...

    我的电脑界面增加程序快捷方式

    3. **创建新的键**:右击 `CLSID` 文件夹,选择“新建”-&gt;“项”,命名为 `{65C998C8-C7D2-46C0-98F6-1E96574A5302}`(这是一个GUID,用于唯一标识这个新创建的对象)。 4. **设置默认值**:双击新创建的键,将其...

    中望CAD快捷键.pdf

    - CTRL + N:新建文件(NNNew)。 - CTRL + O:打开现有文件(OPEN)。 - CTRL + P:打印当前图纸(PRINT)。 - CTRL + Q:退出程序(QuitEXIT)。 - CTRL + S:保存当前图纸(SAVESAve)。 - CTRL + T:打开或关闭...

    vue-cli下的vuex的简单Demo图解(实现加1减1操作)

    2.在项目目录中构建vuex目录(这里我新建了store的文件夹,里面新建了store.js文件) 3.在vue项目中的入口文件main.js中,为实例化的 Vue对象添加 store对象 4.配置和编写store.js文件 5.组件中使用vuex中存放的...

    CAD常用的快捷键命令大全.docx

    在使用过程中遇到任何疑问时,可以通过按下F1键来获取相关的帮助文档或者指南,这对于初学者来说非常实用。 - **F2**: 在作图窗口与文本窗口之间进行切换。这对于查看详细信息或编辑文本时非常方便。 - **F3**: 控制...

Global site tag (gtag.js) - Google Analytics