This question already has answers here:
private method in inheritance in Java
(6 answers)
How can a derived class invoke private method of base class?
(7 answers)
Closed 5 years ago.
public class A {
private void getHello(){
System.out.println("Prints A");
}
}
class B extends A {
public void getHello(){
System.out.println("Prints B");
}
}
class Test{
public static void main(String[] args) {
A a = new B();
}
}
I am creating private method in class A
creating public method with same name in class B by extending class A
Even after creating object for B with A reference
why I am not able to call getHello()?
getHello method is private for class A and you may call it only from this class.
Even if create an instance of class A in some other class you will not be able to access getHello() method.
This is also invalid code.
class Test {
public static void main(String[] args) {
A a = new A();
a.getHello();
}
}
Here is Java documentation.
Be declaring it as a type of A you are losing the implementation details of B although there still there.
A a = new B(); // a.getHello() is not accessible because it looks it up in A
B b = new B(); // a.getHello() is accessible because it calls it in B
Even if the getHello() method would be public in A it would still call it for the instance of B.
As Java Language Specification (https://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6) states:
A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. It is not inherited by subclasses.
When you create a reference to object of A class it is not possible to get access to this method from outside of this class in your case.
Related
This question already has answers here:
Can we create an object of an interface?
(6 answers)
Closed 7 years ago.
Is it possible to create an instance of an interface in Java?
Somewhere I have read that using inner anonymous class we can do it as shown below:
interface Test {
public void wish();
}
class Main {
public static void main(String[] args) {
Test t = new Test() {
public void wish() {
System.out.println("output: hello how r u");
}
};
t.wish();
}
}
cmd> javac Main.java
cmd> java Main
output: hello how r u
Is it correct here?
You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface. For example,
public interface A
{
}
public class B implements A
{
}
public static void main(String[] args)
{
A test = new B();
//A test = new A(); // wont compile
}
What you did above was create an Anonymous class that implements the interface. You are creating an Anonymous object, not an object of type interface Test.
Yes, your example is correct. Anonymous classes can implement interfaces, and that's the only time I can think of that you'll see a class implementing an interface without the "implements" keyword. Check out another code sample right here:
interface ProgrammerInterview {
public void read();
}
class Website {
ProgrammerInterview p = new ProgrammerInterview() {
public void read() {
System.out.println("interface ProgrammerInterview class implementer");
}
};
}
This works fine. Was taken from this page:
http://www.programmerinterview.com/index.php/java-questions/anonymous-class-interface/
Normaly, you can create a reference for an interface. But you cant create an instance for interface.
Short answer...yes. You can use an anonymous class when you initialize a variable.
Take a look at this question: Anonymous vs named inner classes? - best practices?
No in my opinion , you can create a reference variable of an interface but you can not create an instance of an interface just like an abstract class.
Yes it is correct. you can do it with an inner class.
Yes we can, "Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name"->>Java Doc
This question already has answers here:
What is the difference between public, protected, package-private and private in Java?
(30 answers)
Closed 2 years ago.
Suppose i have the following class structure. If i execute the child class, it will print both.
Inside Public method
Inside Private method
Could anyone explain the reason how the private method code is reachable to m1 ?
class Base
{
public void m1()
{
System.out.println("Inside Public method");
m2();
}
private void m2()
{
System.out.println("Inside Private method");
}
}
public class Child extends Base
{
public static void main(String[] args)
{
Child ob = new Child();
ob.m1();
}
}
Private variables/methods are accessible by everything within the class.
Protected variables/methods are accessible by everything within that package and any subclasses.
Public variables/methods are accessible by everything.
A private method is only visible in the class scope. The method m1 is in the same class as the private method m2 even if the m1 method is inherited.
You can do this with a reflection, what you can see here:
Method method = c.getDeclaredMethod("m2", null);
method.setAccessible(true);
method.invoke(obj, null);
Any way to Invoke a private method?
Private methods can be called by any method inside the class it is contained.
You can't call m2 method directly outside of the Base class scope, but you can call it indirectly through less restricted methods like public or protected.
Like you did with m1 method.
The caller class could not call m1 directly, but it will certain execute it. This is known as encapsulation. You use it to hide implementation details that doesn't matter for the caller.
This question already has answers here:
Multiple inheritance for an anonymous class
(6 answers)
Closed 4 years ago.
It is clearly stated that interfaces don't have constructors. But when using anonymous inner classes we create an interface object and do overriding it methods. If there is no constructors in interfaces how this is possible.
For an example,
interface A{
void print();
}
class B{
public static void main(String args[]){
A a=new A(){
void print(){
System.out.println("Message");
}
};
}
}
How that A a=new A() is possible if interface is not having constructors?
The code
interface A {
void print();
}
class B {
public static void main(String[] args) {
A a = new A() {
public void print() {
System.out.println("Message");
}
};
}
}
is a shorthand for
interface A {
void print();
}
class B {
public static void main(String[] args) {
class B$1 extends java.lang.Object implements A {
B$1() {
super();
}
public void print() {
System.out.println("Message");
}
}
A a = new B$1();
}
}
With just one exception: If class B$1 is declared explicitly, it is possible to extend from it using class C extends B$1. However, it is not possible to extend from an anonymous class B$1 (JLS §8.1.4), even though it is not final (JLS §8.1.1.2).
That is, anonymous classes are still classes. As all classes (except java.lang.Object itself), even these classes extend java.lang.Object, directly or indirectly. If an anonymous class is specified using an interface, it extends java.lang.Object and implements that interface. If an anonymous class is specified using a class, it extends that class. In case the constuctor has arguments, the arguments are forwarded to super().
You can even (although definitely not recommended at all) insert a A a2 = new B$1(); later in main(), if you like. But really, don't do that, I'm just mentioning it to show what's going on under the hood.
You can observe this yourself by putting your source code in a separate directory, say, into AB.java, compile it, and then
look at the class files that were generated.
Use javap -c B$1 to see how the anonymous class was generated by javac.
Every class has a default constructor which is the no-argument constructor if you don't define another constructor. And the anonymous class implement the interface will automatically generate it unless you define another constructor.
This question already has answers here:
Why does a sub-class class of a class have to be static in order to initialize the sub-class in the constructor of the class?
(2 answers)
Closed 5 years ago.
Error occur when class C extends B. But, when I write new A().super(); problem is solved. Please consider following code:
public class A {
public class B extends A {
public class C extends B {
public C() {
// No enclosing instance of type A is available due to some intermediate constructor error
// new A().super();
}
}
}
}
My question is why class C cannot extend Class B? Why calling new A().super(); solved the problem? What does it mean? Is there better way to solve it (without using static nested class)?
Simplest code snippet which will be compiled and executed printing 'OK':
public class A {
public class B extends A {
public class C extends B {
public C() {
System.out.println("OK");
}
}
}
public static void main(String[] args) {
new A().new B().new C();
}
}
Here is another example of instantiation of A, B and C. That is, class C can extend Class B as of initial code snippet from your question. Your code is correct in terms of syntax, and can be compiled without adding any unnecessary new A().super()
For consideration, let's refer to the tutorial for inner classes, those by definition are non-static. For static case the correct name is static nested class
An instance of InnerClass can exist only within an instance of OuterClass
To instantiate an inner class, you must first instantiate the outer class
That means, that inner class exists only in context of particular OuterClass instance rather than OuterClass class, that's why new A() does solve the problem, providing runtime instance within which classes B and C do exist
This question already has answers here:
Are static methods inherited in Java?
(15 answers)
Closed 7 years ago.
Why is it possible to get access to the static method of my super class from child instance?
public class Test {
public static void main(String[] args) {
new UtilImpl().fun();
new AbstractUtil() {}.fun();
}
static abstract class AbstractUtil {
public static void fun() {
System.out.println("Fun!");
}
}
static class UtilImpl extends AbstractUtil {
}
}
I can agree with access to the static method of parent class from an instance of the parent class. But if I instantiate a child class, it's weird to have access to the static context of the parent class.
PS
And what are advantages of calling the static method on instance?
In Java, it is allowed to call static methods with an instance variable. This is defined in JLS section 8.4.3.2, quoting:
A method that is declared static is called a class method.
A class method is always invoked without reference to a particular object.
In such a case, Java will actually discard the instance you used and call the static method.
Example 15.12.4.1-1 expresses this in the following way:
When a target reference is computed and then discarded because the
invocation mode is static, the reference is not examined to see
whether it is null:
class Test1 {
static void mountain() {
System.out.println("Monadnock");
}
static Test1 favorite(){
System.out.print("Mount ");
return null;
}
public static void main(String[] args) {
favorite().mountain();
}
}
which prints:
Mount Monadnock
Here favorite() returns null, yet no NullPointerException is thrown.
It's called inheritance. A subclass inherits public members of the parent class, including static methods. The important thing is that the static method is not bound to any instance. You could just do:
UtilImpl.fun();
AbstractUtil.fun();
As far as the compiler is concerned, it's the same thing. The only difference is that your code creates objects but these are not relevant to the way the methods are called (plus as #Dici said in the comments you should have also gotten a warning from the compiler).