注意:super() 和this() 代码不能共存都必须在首行都必须在首行,但是实际效果其实是可以的,如果不写 super 也会自动调用
总结
super 指父类对象,对比 this 关键字,使用方法都一样
super 和 this 代码不能共存都必须在首行都必须在首行,但是实际效果其实是可以的,如果不写 super 也会自动调用
父类的属性要交给父类的构造方法去操作,没什么事就不要去使用 super 来调用父类的构造方法了
final 关键字
概述
final 表示最终的,用来修饰变量,方法和类
COPY
1、final 修饰的局部变量只能被赋值一次 2、final 修饰的成员变量只能被赋值一次,并且必须在声明时就赋值 3、final 修饰的基本类型变量是一个常量(只能被赋值一次),引用类型变量不可修改地址,如对象 4、final 修饰的方法不能被重写 5、final 修饰的类不能被继承 package com.fc.j._final; /* * final修饰的局部变量 */ public class FinalDemo1 { public static void main(String[] args) { // 测试final修饰的修饰的变量 final int num;
num = 10;
System.out.println(num);
/* * 被final修饰的变量只能赋值一次 * * The final local variable num may already have been assigned * * 被final修饰的局部变量num可能已经被赋值 */ // num = 20; } }
// final修饰的类不能被继承,断子绝孙 class Father { /* * final 修饰的成员变量必须在声明时就赋值 * * The blank final field age may not have been initialized * 空白的final成员变量可能未被初始化 */ // final int age; final int age = 16;
public final void play() { System.out.println("下棋"); } }
class Son extends Father { /* * Cannot override the final method from Father * 无法重写被final修饰的方法 */ // @Override // public final void play() { // // } }
特点
final 修饰可以保证安全性,比如数组的长度属性,String 类,这些都是 final 修饰的,保证不可变
/* * Cannot make a static reference to the non-static field Person.name * * 将name添加static后没有报错 */ // System.out.println("没有对象:" + Person.name);
/* * 通过对象调用statice修饰的成员方法 * * The static method test() from the type Person should be accessed in a static way */ // person1.testStatic();
// 通过类名直接调用静态方法 Person.testStatic(); } }
总结
COPY
1、通过类名调用静态成员变量,因为静态变量与对象无关 2、静态变量被所有对象共享,一处更改处处更改
static 方法
static 方法一般称作静态方法,由于静态方法不依赖于任何对象就可以进行访问,因此对于静态方法来说,是没有 this 的,因为它不依附于任何对象,既然都没有对象,就谈不上 this 了。并且由于这个特性,在静态方法中不能访问类的非静态成员变量和非静态成员方法,因为非静态成员方法/变量都是必须依赖具体的对象才能够被调用。
// 自定义static修饰的成员方法 publicstaticvoidtestStatic() { /* * 静态方法不能调用非静态方法 * Cannot make a static reference to the non-static method test() from the type Person */ // test(); System.out.println("static mothed");
/* * 不能再静态方法中使用this关键字 * * Cannot use this in a static context */ // this.name; }