Core java interview Questions You'll Most Likely Be Asked (Second Edition)


Download 1.52 Mb.
Pdf ko'rish
bet44/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   40   41   42   43   44   45   46   47   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

111.



112.
a.
b.
CHAPTER
10
Packages and Access Control
What is a package? What are the advantages of
packages?
Answer:
A package is a collection of related Java types. So, a package
can include related classes, interfaces and enumerations. Having
a package has several advantages as follows:
Packages help to keep related code together.
A package helps avoiding naming collisions. So, you can
have a class or some other Java type with the same name in
different packages.
Packages also help to control access. Code that is outside the
package cannot access code within the package unless
explicitly allowed via the public keyword.
Explain the Java access specifiers.
Answer:
Access specifiers control where a particular member is
accessible. They are just some keywords that are specified with
class members. They can be specified with an instance field as
well as a method. Java has 4 access specifiers as follows:
Private: A member having the private access specifier is
accessible only from within the class in which it is declared.
Protected: A member having the protected access specifier
is accessible to all classes within the package as well as


c.
d.
113.
114.
a.
sub–classes that are outside the package.
Public: A member having the public access specifier is
accessible to all classes outside the package.
Default: The default access occurs when none of the above
access specifiers are specified. In such a case, the member
is accessible within the package but not outside the package.
Explain with a code sample how to create a package.
Answer:
You can create a package by using the package keyword. It
should be followed by the name that you want to give to the
package. The package name should be a valid Java identifier.
The package statement should be the first statement in the java
file. The following code demonstrates this:
package demo;
public class MyClass {
//instance fields and methods
}
This code declares a class called MyClass. It is in a package
called demo. Note that the package statement is the first
statement in the code.

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   40   41   42   43   44   45   46   47   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling