JAVA学习知识记录

这篇博客详细介绍了Java编程的基础知识,包括静态与方法的调用、static的使用、对象和类的区别、构造方法、参数传递、this关键字的应用、继承、方法重写、多态的概念以及如何通过向下转型访问子类特有方法。还涵盖了final关键字、数组、内部类、抽象类、接口、Calender类的使用,异常处理和线程的基本概念。
摘要由CSDN通过智能技术生成

静态与方法

调用静态和非静态方法:

调用非静态方法:也就是没有static修饰的方法体数据,需要进行【类 引用 = new 类名()】进行数据的实例化,然后通过【引用.方法名】进行调用。

调用静态方法:也就是有static修饰的方法体数据,直接通过【类名.方法名】调用

public class Customer {
//  姓名 :
  String name;

//  无参构造方法
  public Customer(){}

//  不带有static关键字的非静态方法
  public void buyGoods(){
    System.out.println(this.name+"在购物");
  }

//  带有static关键字的静态方法
  public static void toGoods(){
    System.out.println(123456);
  }
}
package textThis;

/**
 * @author Monopkr
 * @date 2022/5/14 - 9:10
 */
public class CustomerText {
  public static void main(String[] args) {
// 调用非静态的方法
    Customer c1 = new Customer();
    c1.name = "张三";
    System.out.println(c1.name);
    c1.buyGoods();  // 可以对应修改到对应的name

    Customer c2 = new Customer();
    c2.name = "李四";
    System.out.println(c2.name);
    c2.buyGoods();

//调用static静态方法
    Customer.toGoods();
  }
}

 综合:

package textThis;
/**
 * @author Monopkr
 * @date 2022/5/14 - 11:58
 */
public class CText {

  public void doMethod1(){
    System.out.println("这里是非静态的一级方法");
    this.methods1();  // 调用二级非静态方法
    CText.method2();  // 调用二级静态方法
  }

  public static void doMethod2(){
    System.out.println("这里是静态的一级方法");
    CText T1 = new CText();  // 调用二级非静态方法
    T1.methods1();
    CText.method2();  // 调用二级静态方法
  }

  public static void main(String[] args) {
    CText T = new CText();
    T.doMethod1();
    System.out.println("--------------------");
    CText.doMethod2();
  }

  public void methods1(){
    System.out.println("二级非静态方法");
  }

  public static void method2(){
    System.out.println("二级静态方法");
  }
}

带有static的方法,其实既可以采用类名的方式访问,也可以采用引用的方式访问,但是即使采用引用的方式去访问,实际上执行的时候和引用指向的对象无关。不会出现空指针异常。

 static的使用

静态变量:static修饰的变量: 如:static String country;  在类加载的时候初始化,不需要实例化对象,内存就开辟了。

静态代码块:

1、 语法格式:    static{

                                    java语句;   

                            }

2、静态代码块在类加载时执行,并且只执行一次。

3、静态代码块在一个类中可以编写多个,并且遵循自上而下的顺序依次执行。

4、静态代码块的作用:

public class staticText{
    static{
        System.out.println("类加载");
    }
    
    public static void main (String[] args){
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值