本文共 1496 字,大约阅读时间需要 4 分钟。
匿名对象即无名对象,直接使用new关键字来创建对象
案例代码
package com.itheima_01;/* * 匿名对象:没有名字的对象 * 匿名对象的应用场景: * 当方法只调用一次的时候可以使用匿名对象 * 可以当作参数进行传递,但是无法在传参之前做其他的事情 * * 注意:匿名对象可以调用成员变量并赋值,但是赋值并没有意义 * */public class AnonymousObejctDemo { public static void main(String[] args) { //Student s = new Student(); //s.study(); //s.study(); //s.study(); //new Student();//匿名对象,没有变量引用的对象 //new Student().study(); //new Student().study(); //new Student().study(); //new Student().age = 18; //System.out.println(new Student().age); //Student s = new Student(); //s.age = 18; //s.name = "张三"; //method(s); method(new Student()); } public static void method(Student s) { } }class Student { String name; int age; public void study() { System.out.println("好好学习,高薪就业"); }}
final: 修饰符,可以用于修饰类、成员方法和成员变量
final所修饰的类:不能被继承,不能有子类
final所修饰的方法:不能被重写
final所修饰的变量:是不可以修改的,是常量
案例代码
package com.itheima_01;/* * final: 修饰符,可以用于修饰类、成员方法和成员变量 * final所修饰的类:不能被继承,不能有子类 * final所修饰的方法:不能被重写 * final所修饰的变量:是不可以修改的,是常量 * * 常量: * 字面值常量:1,2,3 * 自定义常量:被final所修饰的成员变量,一旦初始化则不可改变 * * 注意:自定义常量必须初始化,可以选择显示初始化或者构造初始化 * * */public class FinalDemo { public static void main(String[] args) { //Animal a = new Animal(); //a.eat(); Dog d = new Dog(); //d.eat(); //d.num = 20; System.out.println(d.NUM); }}/*final*/ class Animal { public final void eat() { System.out.println("吃东西"); }}class Dog extends Animal { /*public void eat() {}*/ final int NUM; public Dog() { NUM = 10; }}
转载地址:http://jjjqb.baihongyu.com/