码迷,mamicode.com
首页 > 其他好文 > 详细

第2章 匿名对象&final

时间:2018-03-30 15:18:04      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:Java

1.1 匿名对象定义&使用
匿名对象即无名对象,直接使用new关键字来创建对象
1.1.1 案例代码九:

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("好好学习,高薪就业");
}
}

1.2 final关键字
final: 修饰符,可以用于修饰类、成员方法和成员变量
final所修饰的类:不能被继承,不能有子类
final所修饰的方法:不能被重写
final所修饰的变量:是不可以修改的,是常量
1.2.1 案例代码十:

 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;
}
}

第2章 匿名对象&final

标签:Java

原文地址:http://blog.51cto.com/13517854/2092930

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!