Java程序常见问题分析|S14(构造函数)

2021年4月14日14:14:50 发表评论 774 次浏览

先决条件–Java构造函数

1)以下程序的输出是什么?

class Helper
{
     private int data;
     private Helper()
     {
         data = 5 ;
     }
}
public class Test
{
     public static void main(String[] args)
     {
         Helper help = new Helper();
         System.out.println(help.data);
     }
}

a)编译错误

b)5

c)运行时错误

d)这些都不是

答案(a)

说明:

私有构造函数不能用于初始化在其定义的类之外的对象, 因为它对于外部类不再可见。

2)以下程序的输出是什么?

public class Test implements Runnable
{
     public void run()
     {
         System.out.printf( " Thread's running " );
     }
  
     try
     {
         public Test()
         {
             Thread.sleep( 5000 );
         }   
     } 
     catch (InterruptedException e) 
     {
         e.printStackTrace();
     }
      
     public static void main(String[] args)
     {
         Test obj = new Test();
         Thread thread = new Thread(obj);
         thread.start();
         System.out.printf( " GFG " );
     }
}

a)GFG线程正在运行

b)线程正在运行GFG

c)编译错误

d)Runtimer错误

答案(C)

说明:

构造函数不能包含在try/catch块内。

3)以下程序的输出是什么?

class Temp
{
     private Temp( int data)
     {
         System.out.printf( " Constructor called " );
     }
     protected static Temp create( int data)
     {
         Temp obj = new Temp(data);
         return obj;
     }
     public void myMethod()
     {
         System.out.printf( " Method called " );
     }
}
  
public class Test
{
     public static void main(String[] args)
     {
         Temp obj = Temp.create( 20 );
         obj.myMethod();
     }
}

a)构造方法称为

b)编译错误

c)运行时错误

d)以上都不是

答案(a)

说明:

当构造函数被标记为私有时, 从某个外部类创建该类的新对象的唯一方法是使用程序中上面定义的创建新对象的方法。 create()方法负责从其他一些外部类创建Temp对象。创建对象后, 可以从创建对象的类中调用其方法。

4)以下程序的输出是什么?

public class Test
{
     public Test()
     {
         System.out.printf( "1" );
         new Test( 10 );
         System.out.printf( "5" );
     }
     public Test( int temp)
     {
         System.out.printf( "2" );
         new Test( 10 , 20 );
         System.out.printf( "4" );
     }
     public Test( int data, int temp)
     {
         System.out.printf( "3" );
          
     }
      
     public static void main(String[] args)
     {
         Test obj = new Test();
          
     }
      
}

a)12345

b)编译错误

c)15

d)运行时错误

答案(a)

说明:

构造函数可以链接和超载。调用Test()时, 它将创建另一个调用构造函数Test(int temp)的Test对象。

5)以下程序的输出是什么?

class Base
{
     public static String s = " Super Class " ;
     public Base()
     {
         System.out.printf( "1" );
     }
}
public class Derived extends Base
{
     public Derived()
     {
         System.out.printf( "2" );
         super ();
     }
      
     public static void main(String[] args)
     {
         Derived obj = new Derived();
         System.out.printf(s);
     }
}

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: