看程序写结果

本文通过一系列示例代码探讨了Java编程中的类构造过程,包括静态代码块、构造代码块、构造方法以及this和super关键字的使用。详细解释了对象创建时的执行顺序,如静态初始化块、普通初始化块、构造方法的调用,并讨论了继承、内部类以及接口的实现和继承等核心概念。
摘要由CSDN通过智能技术生成

1.(静态代码块)

class Student{
    static{System.out.println("Student的静态代码块1") ;}
    public Student(){
        System.out.println("Student的无参构造方法") ;
    }
    {System.out.println("Student的构造代码块1") ;}
    {System.out.println("Student的构造代码块2") ;}
    public Student(String str){
        System.out.println("Student的有参构造方法") ;
    }
    static{System.out.println("Student的静态代码块2") ;} 
}
class StudentTest{
    static{System.out.println("高圆圆已经42了,我很伤心") ;}
    public static void main(String[] args){
          Student s = new Student() ;
          Student s2 = new Student("hello") ;
    }
}


高圆圆已经42了,我很伤心
Student的静态代码块1
Student的静态代码块2
Student的构造代码块1
Student的构造代码块2
Student的无参构造方法
Student的构造代码块1
Student的构造代码块2
Student的有参构造方法

2.(this  super)

需要在控制台分别打印30,20,10

        class Test{
        public static void main(String[] args){

            Zi zi = new Zi();
            zi.show() ;    
        }
        }

        class Fu{
            int num = 10;
        }
        class Zi extends Fu{
            int num = 20 ;
            public void show(){
            int num = 30 ;
            //补全代码


        System.out.println(num);//30
        System.out.println(this.num);//20
        System.out.println(super.num);//10
        }
        }

 3.(继承、对象构造过程)

有以下代码
class Meal{
public Meal(){
    System.out.println("Meal()");

}
class Lunch extends Meal{
public Lunch(){
    System.out.println("Lunch()");
}    
}
class Vegetable {
public Vegetable(){
    System.out.println("Vegetable()");

}
class Potato extends Vegetable{
public Potato(){
    System.out.println("Potato()");

}
class Tomato extends Vegetable{
public Tomato(){
    System.out.println("Tomato()");

}
class Meat{
public Meat(){
    System.out.println("Meat()");

}
class Sandwich extends Lunch{
    Potato p = new Potato();
    Meat m = new Meat();
    Tomato t = new Tomato();
    public Sandwich(){
    System.out.println("Sandwich()");
    } 
}
public class TestSandwich{
    public static void main(String args[]){
    Sandwich s = new Sandwich();
    } 
}
写出这段代码的输出结果。


Meal()
Lunch()
Vegetable()
Potato()
Meat()
Vegetable()
Tomato()
Sandwich()

 4.

看程序,写结果:(请说明原因)
  class Root {
  static {
    System.out.println("Root的静态初始化块");
  }
 
  {
    System.out.println("Root的普通初始化块

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值