• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

Question

 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class Outer {
private Outer() {
System.out.println("Executing Step1");
}
public void Outer() {
System.out.println("Executing Step2");
}
}
public class q2 extends Outer {
public static void main (String[] args) {
Outer t = new Outer();
t.Outer();
}
}

what is the output of this code and why is it so.
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The code does not compile since the default constructor of Outer is private and thus not usable outside the Outer class.
If you change the modifier private to public for the default constructor the output is
Executing Step1
Executing Step2
which makes sense, the first line is written when the constructor is called and the second when you call the method Outer !
But this is poor design to name a method the same name as the class name since it can be misleading and error-prone.

------------------
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform
 
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This code doesn't compile because the constructor is private.
Yes it seems that the compiler doesn't complain having a method with the same name as the Class or even an identifier for a field:
int Outer; //I have checked it out
 
get schwifty. tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic