Java 程序运行结果分析:15 道经典例题详解

本文包含 15 道 Java 程序运行结果分析例题,涵盖继承、接口、方法重写、变量作用域、构造函数、静态变量等核心概念。通过详细解析,帮助你理解 Java 程序执行过程,提升编程能力。

1. 下面程序运行的结果是 'B info'

public class A {
    public void info(){
        System.out.println('A info');
    }
}
public class B extends A{
    public void info(){
        System.out.println('B info');
    }
    public static void main(String[] args) {
        B b = new B();
        A a = b;
        a.info();
    }
}

解析:

  • 由于 B 类继承了 A 类,并且 B 类重写了 info() 方法,所以当 a.info() 被调用时,实际执行的是 B 类中的 info() 方法。

2. 下面程序运行的结果是 'foofoofoofoofoo'

public class Base {
    public static final String FOO = 'foo';
    public static void main(String[] args) {
        Base b = new Base();
        Sub s = new Sub();
        System.out.print(Base.FOO);
        System.out.print(Sub.FOO);
        System.out.print(b.FOO);
        System.out.print(s.FOO);
        System.out.print(((Base) s).FOO);
    }
}
class Sub extends Base {
    public static final String FOO = 'bar';
}

解析:

  • FOO 是一个静态常量,属于类属性,因此无论创建多少个对象,都共享同一个 FOO
  • Sub 类继承了 Base 类,但是重写了 FOO 的值。
  • main 方法中,访问 FOO 时,会根据具体的对象类型进行判断。

3. 下面程序运行的结果是 'A info Sub.f() Super.f()'

class Super{
    private void f() { System.out.println('Super.f()');}
    public void g() { f(); }
    public void k() { f(); }
}
public class Sub extends Super {
    private void f() { System.out.println('Sub.f()');}
    public void k() { f();}
    public static void main(String[] ar) {
        Super obj = new Sub();
        obj.g();
        obj.k();
    }
}

解析:

  • Sub 类继承了 Super 类,并重写了 f() 方法。
  • obj 变量指向一个 Sub 类的对象,但它的类型是 Super 类。
  • 调用 g() 方法,因为 Super 类中 f() 方法是 private 的,所以调用的是 Super 类中的 f() 方法。
  • 调用 k() 方法,因为 Sub 类中 f() 方法是 private 的,所以调用的是 Sub 类中的 f() 方法。

4. 下面程序运行的结果是 's=7'

interface DeclareStuff {
    public static final int EASY = 3;
    void doStuff(int t);
}
public class TestDeclare implements DeclareStuff {
    public static void main(String[] args) {
        int x = 5;
        new TestDeclare().doStuff(++x);
    }
    public void doStuff(int s) {
        s += EASY + (++s);
        System.out.println('s=' + s);
    }
}

解析:

  • doStuff 方法的参数 s 在方法内部进行修改,并不会影响 main 方法中的 x 变量。
  • ++x 为前置自增运算,执行 doStuff 方法时,x 的值为 6。
  • s += EASY + (++s) 中的 ++s 为前置自增运算,s 的值会先自增 1 变成 7,然后再参与加法运算,最终 s 的值为 7。

5. 下面程序运行的结果是 '100 100 100 100'

interface InterfaceA{  int max = 100; }
class ClassA implements InterfaceA{ }
class ClassB extends ClassA{  }
public class Test{
    public static void main(String[] ar) {
        ClassB b = new ClassB();
        System.out.print(b.max);
        System.out.print(' ' + ClassB.max);
        System.out.print(' ' + ClassA.max);
        System.out.print(' ' + InterfaceA.max);
    }
}

解析:

  • max 是接口 InterfaceA 中的静态常量,属于类属性,因此无论创建多少个对象,都共享同一个 max
  • ClassAClassB 都实现了接口 InterfaceA,因此它们都拥有 max 属性。

6. 下面程序的执行结果为 'no Exception finally Catch finally'

public class Test{
    static void Proc(int sel){
        try{
            if (sel == 0){ System.out.println('no Exception'); return ;}
            else if (sel == 1){ int i = 0; int j = 4 / i; }
        }catch(ArithmeticException ex){
            System.out.println('Catch  ');
        }catch(Exception ex){
            System.out.println('Will not be executed');
        }finally{
            System.out.println('finally');
        }
    }
    public static void main(String[] ar){
        Proc(0);   Proc(1);
    }
}

解析:

  • sel 为 0 时,程序不会抛出异常,所以直接执行 return 语句,跳出 try-catch-finally 块,仅打印 'no Exception finally'。
  • sel 为 1 时,程序会抛出 ArithmeticException 异常,被 catch(ArithmeticException ex) 捕获,打印 'Catch finally'。
  • finally 块无论是否发生异常都会执行。

7. 下面程序的执行结果为 'student'

class Person{
    String name = 'person';
    public void shout(){
        System.out.print(name);
    }
}
class Student extends Person{
    String name = 'student';
    String school = 'school';
    public void shout() { 
        System.out.print(name);
    }
}
public class Test2{
    public static void main(String[] args){
        Person p = new Student();
        p.shout();
    }
}

解析:

  • Student 类继承了 Person 类,并且重写了 shout() 方法。
  • p 变量指向一个 Student 类的对象,但它的类型是 Person 类。
  • 调用 shout() 方法,由于 Student 类重写了 shout() 方法,所以实际执行的是 Student 类中的 shout() 方法。

8. 以下程序的输出结果为 '汤姆猫体重:20.0斤'

public class Tom{
    private float weight;
    private static String name;
    public void setWeight(float weight){ this.weight =  weight;}
    private void  out(){
        System.out.println(name + '体重:'+ weight+'斤');
    }
    public static void main(String[] ar){
        Tome.name = '汤姆猫';
        Tom cat = new Tom();
        cat.setWeight(20);
        cat.out();
    }
}

解析:

  • name 是一个静态变量,属于类属性,因此所有 Tom 类的对象都共享同一个 name
  • weight 是一个实例变量,属于对象属性,每个 Tom 类的对象都拥有自己的 weight

9. 以下程序的输出结果为 '15 8.0'

class A{
    double f(double x,double y){return x + y;}
}
class B extends A{
    double f(int x,int y){  return x * y;   }
}
public class Test{
    public static void main(String[] ar){
        B b = new B();
        System.out.println(b.f(3,5));
        System.out.println(b.f(3.0,5.0));
    }
}

解析:

  • B 类继承了 A 类,并且重写了 f() 方法。
  • f(int x,int y) 方法是 B 类特有的,所以调用 b.f(3,5) 会执行 B 类中的 f() 方法。
  • f(double x,double y) 方法是 A 类中的方法,虽然 B 类也拥有该方法,但是因为参数类型不匹配,所以调用 b.f(3.0,5.0) 会执行 A 类中的 f() 方法。

10. 以下程序的输出结果为 '0 100 0 100'

public class Father{
    int a=100;
    public void miner(){  a--; }
    public static void main(String[] args){
        Father x = new Father();
        Son y = new Son();
        System.out.println(y.a);
        System.out.println( y.getA());
        y.miner();
        System.out.println(y.a);
        System.out.println(y.getA());
    }
}
class Son extends Father{
    int a = 0;
    public void plus(){ a++; }
    public int getA() { return super.a; }
}

解析:

  • Son 类继承了 Father 类,并且拥有自己的 a 属性。
  • y 变量指向一个 Son 类的对象,所以访问 y.a 会访问 Son 类中的 a 属性。
  • getA() 方法会访问 Father 类中的 a 属性,所以访问 y.getA() 会访问 Father 类中的 a 属性。
  • 调用 miner() 方法时,会修改 Father 类中的 a 属性。

11. 下面程序运行的结果是 'The value is 10 The value is 9 The value is 8 The value is 7 The value is 6 The value is 5 The value is 4 The value is 3 The value is 2 The value is 1 The value is 0 The value is -1 The value is -2 The value is -3 The value is -4 The value is -5 The value is -6 The value is -7 The value is -8 The value is -9 The value is -10'

public class Test{
    void printValue(int m){
        do{
            System .out .println('The value is'+m);
        }while(- - m>10);
    }
    public static void main(String arg[]){
        int i=10;
        Test t= new Test();
        t.printValue(i);
    }
}

解析:

  • --m 是后置自减运算,在循环体中执行 System.out.println('The value is'+m) 后,m 的值才会自减 1。
  • 循环条件是 --m > 10,当 m 自减后小于等于 10 时,循环结束。

12. 下面程序运行的结果是 'Animal Dog'

class Animal {
    Animal() { System.out.print('Animal '); }
}
public class Dog extends Animal {
    Dog() { System.out.print('Dog '); }
    public static void main(String[] args) {
        Dog snoppy= new Dog();
    }
}

解析:

  • 当创建 Dog 类的对象时,会先执行 Animal 类的构造函数,然后执行 Dog 类的构造函数。

13. 下面程序运行的结果是 '10'

class Creature{
    private static long numCreate = 0;
    public Creature() { numCreate++; }
    public static long numCreated() { return numCreate; }
}
public class Creator{    
    public static void main(String[] ar) {
        Creature creature;
        for (int i = 0;i < 10;i++)
            creature = new Creature();
        System.out.println(Creature.numCreated());
    }
}

解析:

  • numCreate 是一个静态变量,属于类属性,因此所有 Creature 类的对象都共享同一个 numCreate
  • 每次创建 Creature 类的对象时,numCreate 都会自增 1。

14. 下面程序运行的结果是 '20 10'

class TT{
    int num;
    public TT(int n) { num = n;  }
    public void display() {   System.out.println(num);  }
    public void setNum(int n) { num = n;    }
}
public class Test{
    TT tt = new TT(10);
    int num = 10;
    public static void main(String[] ar) {
        Test  ex = new Test();
        ex.change(ex.tt,ex.num);
        ex.tt.display();
        System.out.println(ex.num);
    }
    public void change(TT t,int n) { t.setNum(20); n += 2; }
}

解析:

  • change 方法中的参数 tn 是局部变量,它们是方法内部独立的,不会影响 Test 类中的 ttnum 变量。
  • change 方法中修改了 tnum 值,但不会影响 Test 类中的 tt 变量。

15. 下面程序运行的结果是 'Hello good-bye'

class Teacher{
    int var;
    Teacher(double var){  this.var = (int)var;}
    Teacher(int var){    this('good-bye');}
    Teacher(String str){    this();
        System.out.println(str);
    }
    Teacher(){    System.out.println('Hello');
    }
    public static void main(String[] ar) {
        new Teacher(15);
    }
}

解析:

  • 构造函数调用顺序:
    • new Teacher(15) 调用 Teacher(int var) 构造函数。
    • Teacher(int var) 调用 Teacher(String str) 构造函数。
    • Teacher(String str) 调用 Teacher() 构造函数。
    • Teacher() 构造函数打印 'Hello'。
    • Teacher(String str) 构造函数打印 'good-bye'。

16. 下面程序的执行结果为 '15.0 8'

interface A{  double f(double x,double y);}
class B implements A{
    public double f(double x,double y){  return x * y; }
    int g(int a,int b){return a + b; }
}
public class Test{
    public static void main(String[] ar){
        A a = new B();   System.out.println(a.f(3,5));
        B b = (B)a;      System.out.println(b.g(3,5));
    }
}

解析:

  • a 变量指向一个 B 类的对象,但它的类型是 A 类。
  • f() 方法是接口 A 中定义的方法,所以调用 a.f(3,5) 会执行 B 类中的 f() 方法。
  • g() 方法是 B 类特有的,所以调用 b.g(3,5) 会执行 B 类中的 g() 方法。

17. 下面程序的运行结果是 'Welcome'

public class welcomeTest {
    public static void main(String[] args) {
        String s, s1 = '';
        char c;
        s = 'wELCOME';
        for (int i = 0; i < s.length(); i++) {
            c = s.charAt(i);
            if (c >= 'a' && c <= 'z') {
                s1 = s1 + Character.toUpperCase(c);
            } else {
                s1 = s1 + Character.toLowerCase(c);
            }
        }
        System.out.println(s1);
    }
}

解析:

  • 程序会遍历字符串 s 中的每个字符,判断字符的大小写,并将其转换成相应的字母大小写。

18. 下面程序的运行结果是 '1 2 4 8'

public class arrTest {
    public static void main(String args[]) {
        int i, j;
        int a[] = {2, 1, 4, 8};
        for (i = 0; i < a.length - 1; i++) {
            int k = i;
            for (j = i; j < a.length; j++)
                if (a[j] < a[k])
                    k = j;
            int temp = a[i];
            a[i] = a[k];
            a[k] = temp;
        }
        for (i = 0; i < a.length; i++)
            System.out.print(a[i] + ' ');
        System.out.println();
    }
}

解析:

  • 程序使用冒泡排序算法,将数组 a 从小到大排序。

19. 下面程序的运行结果是 'true,false'

public class StringTest {
    public static void main(String args[]) {
        String s1 = new String('abcde');
        String s2 = new String('abcde');
        boolean b1 = s1.equals(s2);
        boolean b2 = s1 == s2;
        System.out.print(b1 + ',' + b2);
    }
}

解析:

  • equals() 方法比较的是字符串的内容是否相同。
  • == 运算符比较的是对象的地址是否相同。

20. 下面程序的运行结果是 'a.add=3.0 b.add=3.0'

class A {
    int x=1, y=2;
    double add(){ return x+y; }
}
class B extends A{
    int x=10, y=20;
    double add(){ return super.x + super.y; }
}
class Takecare {
    public static void main(String[] args){
        A a = new A();
        B b = new B();
        System.out.println('a.add='+a.add());
        System.out.println('b.add='+b.add());
    }
}

解析:

  • B 类继承了 A 类,并且重写了 add() 方法。
  • 调用 a.add() 会执行 A 类中的 add() 方法,因为 a 变量指向的是一个 A 类的对象。
  • 调用 b.add() 会执行 B 类中的 add() 方法,但该方法中调用了 super.xsuper.y,所以最终会访问 A 类中的 xy 属性。

希望以上解析对你有帮助!如果你有任何疑问,请随时提问。

Java 程序运行结果分析:15 道经典例题详解

原文地址: https://www.cveoy.top/t/topic/f17h 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录