Java基础之static域访问外部变量和方法

  Java中static方法在访问外部方法和变量时有一些约定,例如:

  static方法中在没有创建对象的情况下是不能直接引用非staitc方法或变量的,否则将会发生编译错误:

  提示说static不能引用非static方法或者变量,好啦,上代码:

  package com.test;

  public class Test1 {

  int a;

  public void printStr()

  {

  System.out.println("Welcome!");

  }

  public static void main(String[] args) {

  System.out.println(a);

  printStr();

  }

  }

  此代码将会发生编译错误,由于在static main方法中访问了外部非static变量a和方法printStr();

  此时只需要将变量a和方法printStr()声明为static即可。

  当然还有另外一种解决方法:通过创建对象来引用外部非static变量和方法,好了,上代码:

  package com.test;

  public class Test1 {

  int a;

  public void printStr()

  {

  System.out.println("Welcome!");

  }

  public static void main(String[] args) {

  Test1 test=new Test1();

  System.out.println(test.a);

  test.printStr();

  }

  }

  疯狂软件教育中心依托开发团队的强大技术实力,把企业最新技术融入实训课程,打造金牌的品质,才能给予学员黄金的未来,疯狂软件凭借过硬的技术实力与丰富的项目开发经验,赢得了社会的肯定。疯狂软件Java培训师资力量强大,课程内容深入,为学员高薪就业做了很好的铺垫,拥有丰富就业指导经验的就业团队也成为了学员高薪就业的先天优势。地址:广州天河区车陂沣宏大厦3楼。

原文地址:https://www.cnblogs.com/gojava/p/3691758.html