• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • paul wheaton
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Tim Holloway
  • Carey Brown
  • salvin francis

overriding

 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
//File A.java
package a;
public class A
{
A(){ }
public void print(){ System.out.println("A"); }
}
//File B.java
package b;
import a.*;
public class B extends A
{
B(){ }
public void print(){ System.out.println("B"); }
public static void main(String[] args)
{
new B();
}
}

What will be printed when you try to compile and run class B?

Select 1 correct option.
a It will print A.
b It will print B.
c It will not compile.
d It will compile but will not run.
e None of the above.


i thought if there is no access modifier to constructor as in class A above,it takes the modifier of the class i.e. public and the ans is e.
But the given ans is c.
Can anybody plz tell me why this?
 
Ranch Hand
Posts: 2410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If a default constructor is created for the class, it has the same access modifier as the class.

But if you create a no argument constructor, you can declare its level of access.

In this case, you get a compile-time error because the no argument constructor in class A is not accessible outside the package containing it.
 
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you don't provide any constructor's then the default constructor provided by the compiler will have the access modifier as that of the class.

But here you have provided the no-args default-access contructor so the compiler doesn't provide any constructors and hence the compiler error.
 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
wheni code that code in my comp it can compile.....how come the answer is C???
 
S Thiyanesh
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ming,With the exact package structure the code should not compile until you cahnge the access modifier of the Base class constructor to either protected or public.
 
CAUTION! Do not touch the blades on your neck propeller while they are active. Tiny ad:
professionally read, modify and write PDF files from Java
https://products.aspose.com/pdf/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!