Win a copy of Micro Frontends in Action this week in the Server-Side JavaScript and NodeJS forum!
  • 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
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Public class in file

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How many classes in a single source file can be declared as public?

1) One
2) More than one
3) None

I thought inner classes can be declared as public and choosen the answer as 2 (More than one) in iRix Test1. But the answer is showing wrong. Am I wrong?

 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are correct. The question could have been more clear by asking, "How many top-level classes..."

A source file cannot contain more than 1 top-level class (or interface) that is public. Nested classes are not subject to this constraint.
 
Mvvsatyanarayana Murty
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We can call static inner classes also as Top-level classes, these also we can declare as public.
 
marc weber
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note the terminology in the Java Language Specification...

A nested class is any class whose declaration occurs within the body of another class or interface. A top level class is a class that is not a nested class.


Ref: Chapter 8 - Classes

An inner class is a nested class that is not explicitly or implicitly declared static.


Ref: 8.1.3 Inner Classes and Enclosing Instances

So a "nested" class can be static, but an "inner" class cannot.

A static nested class does not require an instance of the enclosing class, so in that respect it behaves much like a top level class. But because it is nested, it is (by definition) not a top level class. (See JLS quote above.)
 
Quick! Before anybody notices! Cover it up with this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic