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


Download 1.52 Mb.
Pdf ko'rish
bet33/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   29   30   31   32   33   34   35   36   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

084.
085.
Explain static nested classes with a code sample.
Answer:
A static nested class is simply an inner class that has the static
keyword. The following code demonstrates this:
public class MyClass {
int ivalue = 1000; // Line 1
static int staticValue = 10;
static class Nested {
void doSomething() {
staticValue = 6; //Line 2
//ivalue = 20; //Line 3
}
}
}
A static nested class can only access static variables from the
outer class, it cannot access the non–static outer class variables.
So, Line 2 works without any issue, however uncommenting Line
3 will cause a compilation error.
Explain with a code sample how a static nested class can
be instantiated.
Answer:
Consider the following code snippet:
class MyClass {
int ivalue = 1000; //Line 1
static class Nested { //Line 2
}


}
The static nested class can be instantiated as follows:
MyClass.Nested nested = new MyClass.Nested();
To instantiate a static nested class, both the outer class name
and the nested class name need to be specified. In the above
code, the class name is MyClass and the Static Nested class
name is Nested.



086.
087.
CHAPTER
08
Inheritance
Give an example of illegal method overriding.
Answer:
The following code is an example of illegal method overriding:
class Electronics {
public void displayPrice() {}
}
class Camera extends Electronics {
public void displayPrice() throws Exception {}
}
In this code snippet, the class Camera is a sub–class of the
Electronics class. The displayPrice() method is
overridden in the Camera class. However, this code will cause a
compilation error. This is because the displayPrice() method
in Camera class specifies that it throws an Exception. One of the
rules of method overriding is that the overridden method must not
throw a new or a broader checked exception.

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   29   30   31   32   33   34   35   36   ...   171




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