Java不同类方法的调用以及static方法小解

您所在的位置:网站首页 java调用别的类里的函数 Java不同类方法的调用以及static方法小解

Java不同类方法的调用以及static方法小解

2023-12-10 20:37| 来源: 网络整理| 查看: 265

虽然很基础,但我还是写一下. 定义两个类:TestMethod和TestMet,TestMethod内容如下:

package test; public class TestMethod { public static void main(String[] args) { TestMet testMet=new TestMet(); testMet.onD0(); } }

TestMet内容如下:

package test; public class TestMet { public TestMet() { super(); } void onD0() { } }

此时类TestMethod方能调用TestMet中的onDO方法,但是当你这样写时:

package test; public class TestMethod { public static void main(String[] args) { //TestMet testMet=new TestMet(); TestMet.onD0(); } }

报错,提示要将TestMet中的onDO方法改成static,事实上,我想要说的就是static修饰的方法才能用类名.方法调用,如果不是静态方法你还得通过构造器new 类名,才能调用该类的方法. 再来,看下static方法是否真的不能调用本类非静态方法,示例如下: (注意:java类中,如果用户没有一个类创建构造器,java编译器就会自动识别,在jvm中为这个类创建一个默认构造器,这个构造器没有参数。当用户为类创建一个构造器时,不管这个构造器是否有参数,JVM就不再为该类创建一个无参的构造器了,为了防止这个类被其他类继承,所以我们要强调,在为类创建构造器时就要创建一个无参的构造器,以防止子类初始化时,调用父类的默认构造器。所以我们创建的这个无参构造器,也是默认构造器。)

package test; public class TestMethod { void Hello(){} public static void main(String[] args) { TestMet testMet=new TestMet(); testMet.onD0(); Hello(); } }

报错提示:将Hello方法改成static,果真. 静态方法只能调用该类的静态变量?

package test; public class TestMethod { int a=5; public TestMethod() { super(); } public void Hello(){ a=6; aa();//非静态方法可以调用静态方法 } static void aa(){} public static void main(String[] args) { TestMet testMet=new TestMet(); testMet.onD0(); TestMethod testMethod=new TestMethod(); testMethod.Hello(); // testMet.Hello(); // Hello(); } }

确实如此,调用其他类的静态方法和变量试试: 答案是不行,只能通过类名.(静态)方法.



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3