//关键字的使用探讨
/*
访问关键词
private 只能在本类中访问
public 只能在本工程中访问
protected 只能在包中和子类中访问
默认的 只能在包中访问
*/
/*
final 类 方法 变量
final 类 不能被继承
final 方法 不能被子类覆盖,但可以继承
final 变量 只能有一次赋值,赋值后不能改变
final 不能用来修饰构造方法
*/
//this(); 调用本类中的某个方法
public class A{
int age;
public A(int age){
this.age = age;
}
}
//super();调用父类中的方法
public class B extends A{
super();
public B(){
System.out.println("我是B类中的构造方法");
}
}
//例如:
class A{
//final int age =11;fianl会调用构造方法来赋值,此处不需要再赋值
final int age;
public A(){
this.age = 10;
}
}
class testA{
public static void main(String args[]){
A a = new A();
//会出现错误应为age只能赋值一次
}
}
//static 方法 属性 代码块
//static 方法 无需创建对象,直接通过类名来调用
class Test {
static void go() {
System.out.println("Welcome");
}
}
public class Demo {
public static void main(String[] args) {
Test.go();
}
}
//static 属性 表示该类共享同一属性
//定义一个学生类
public class Student {
public Student() {
System.out.println("我是学生类中的构造方法");
}
public static void study() {
System.out.println("学生的学习方法");
}
// 非静态代码块,在对象被创建的时候会执行
{
System.out.println("我是学生类中的代码块");
}
}
//定义一个中学生类
public class MinStudent extends Student {
public static void study() {
System.out.println("中学生的学习方法");
}
}
//定义一个大学生类
public class UNStudent extends Student{
public static void study() {
System.out.println("。。。。大学生的学习方法");
}
}
//定义一测试类
public class Demo {
public static void main(String[] args) {
System.out.println("开始主函数>>>>>>>>>>>");
// Student stu = new UNStudent();
// stu.study();
//
// Student stu1 = new MinStudent();
// stu1.study();
// Student.study();
// UNStudent.study();
// MinStudent.study();
Student stu = new Student();
stu.study();
}
// 静态代码块
static {
System.out.println("我是静态代码块!!!!!!!!!");
}
}
//静态代码块会在加载类的时候就执行,非静态的代码块会在加载main方法之后执行
//static 代码块 加载类的时候执行
class A(){
static{
System.out.println("我是静态代码块");
}
public A(){
System.out.println("我是构造方法");
}
}
public class Demo {
public static void main(String[] args) {
A a = new A();
//此程序会先执行static代码块 ---> 再执行构造方法
}
}
//关于程序执行的顺序
//例如:
//定义一个基类
public class A(){
public A(){
System.out.println("A");
}
}
//定义一个类继承A类
public class B(){
public B(){
System.out.println("B");
}
}
public class C{
public C(){
System.out.println("C");
}
public static A a = new A();
B b = new B();
public static void main(String args[]){
go();
}
public static void go(){
B b1 = new B();
}
}
/*
总结: final 最后的
final 类 不能被继承
final 方法 不能被子类覆盖,但可以继承
final 变量 只能有一次赋值,赋值后不能改变
final 不能用来修辞构造方法
static 静态的
//static 方法 无需创建对象,直接通过类名来调用
//static 属性 表示该类共享同一属性
//static 代码块 加载类的时候执行
访问关键词 :private public protected 默认的
this(); 调用本类中的某个方法
super(); 调用父类中的方法
*/