interface abs{
int a=10;// by default final static
void callme();
}
class B implements abs{
int a =11;// reinitializing
void call()
{
System.out.println("No problem"+a);
}
public void callme()
{
System.out.println("Call me"+a);
}
}
class main{
public static void main(String args[]){
B m=new B();
m.call();
m.callme();
}
}
In Herbert Schildt book, I have read that the interface variables are default Final and static. Which implicitly means that it will act like a constant. but when I am assigning 11 in the variable a in my above mentioned code, it is not giving any error.
o/p
No problem11
Call me11
You're not re-initializing the variable, but you're hiding it.
In order to access abs's a member, you have to refer it with the interface name. Something like:
System.out.println("No problem" + abs.a);
Because you have declared variable again
int a =11;
so see the error you want
do this in your class
a=11;
in your case the a is an entire new variable belonging to class B
You are not modifying the value of abs.a when you initialize a in class B. The field B.a simply hides the inherited a from the interface. You can still get to abs.a from code in class B by using the fully qualified name abs.a.
No, You can't reinitialize Interface variable. The variable in your Implementation Class is not interface variable A, but B class' instance variable. If you want to access Interface variable you reference it as abs.A
What you are actually doing is hiding the variable in interface by declaring a variable with same name in class B. You can verify it by using this code:
public interface Abs {
int a=10;// by default final static
void callme();
default void printA() {
System.out.println("A in interface: " + a);
}
}
public class B implements Abs {
int a =11;// reinitializing
void call()
{
System.out.println("A in class: "+a);
}
public void callme()
{
printA();
}
}
Then we have:
public static void main(String[] args){
B m=new B();
m.call();
m.callme();
}
It prints:
A in class: 11
A in interface: 10
Related
We have an interface and class with no relation each having methods with same signature. These can be related to a class which would compile fine.
interface A {
void test();
}
class B {
public void test() {
System.out.println("Test");
}
}
public class MultipleLevelInheritance extends B implements A {
public static void main(String[] args) {
new MultipleLevelInheritance().test();
}
}
But when we do the same with the a variable its causing ambiguity.
interface A {
int a = 10;
}
class B {
public static int a = 9;
}
public class MultipleLevelInheritance extends B implements A {
public static void main(String[] args) {
System.out.println(a); //The field a is ambiguous
}
}
Even if we keep a as final in B, its still causing the error. Why is that valid for methods and invalid for variables?
When you implement an interface, all variables are inherited in the class. So, when you extend a class and implements the interface, it will have two declaration of variable a. Hence you are getting ambiguity error.
But when it comes to methods, when you implement the interface, you are expected to provide the implementation of the methods defined in interface. In your example, this implementation is provided by class B. Therefore there is no error.
Your class MultipleLevelInheritance is implementing an interface and extending a class, and both have the same property name (a),when you call a in MultipleLevelInheritance, Java is not able to determine if the variable refers to A.a or B.a. you just need to prefix it.
When a static method is called from a reference variable of type A, Java will find yourself where that method?
a) Class which objects are shown to belong
b) Class A
c) Starting from the class that the object is shown to belong, if not see, then look at the superclass.
d) sublayer of A
public class A {
public static void get(){
System.out.println();
}
}
public class B extends A {
public static void get(){
System.out.println("this is Get() method ");
}
}
public static void main(String args[]){
A a=new A();
A b=new B();
a.get();
b.get();
}
In this case the program will print two empty lines because both calls are directed to the static method of class A.
This is because static calls are evaluated not at runtime but a compile time and you can't use override functionality with them.
So in both cases the visible class is "A" thus the static method get() of A will be invoked.
I would like to know how the default package is defined in Java.I know how public and private access is defined but I don't know whether there is any default package access that is defined in package level access in java.
The code I tried to execute is:
class A
{
public static void value()
{
int a;
a=5;
}
public static void main()
{
value();
}
}
class B
{
public void greet()
{
System.out.println("Value of a is"+a);
}
}
The error I got is:
D:\Downloads\pro>javac A.java
A.java:17: error: cannot find symbol
System.out.println("Value of a is"+a);
^
symbol: variable a
location: class B
1 error
Since both classes belong to the same default package shouldn't class B access class A's members(a)?
I'm asking this question because when I compile java file containing two classes since no modifier is given for classes,java compiler would give package level access as the default access modifier for the classes.Since no package is defined,java compiler would use the default package but I couldn't get whether the default package is included in package level access in java.Could anyone help me.
a is a variable inside the static function value and not visible outside of that function at all. Doesn't have to do with access specifiers.
The default package is the package without a name, all classes without a package declaration at the top of the file fall into it.
It is subject to all normal rules of packages except that you can't reference classes of it from a class inside a package.
For example I have 2 java files:
public class A{
public static void foo(){System.out.println("fooCalled");}
}
and
package com.example;
public class B{
public static void main(String[] arg){
A.foo();//won't compile
}
}
Then B (or in the qualified form com.example.B) can never call the foo of A without reflection magic.
Your program has nothing to do with access specifiers, as you have declared your variable int a inside a method.
Thus it becomes just a local variable. You cannot even use it outside this method in the same class.
If we talk specifically about access specifiers then we can have default access specifier in Java which has scope up to the same package only.
package com;
class A{
int a; // this is an instance variable
static int b; //this is a class variable
}
package com;
class B{
//can use a variable here
// To use a here, we need new A().a;
// To use b here, we can do, A.b
}
package hello;
class C{
//can't use a variable here
}
Edit
Suppose we create a file with name MyProgram.java on Desktop. Below is the code of this file,
class First{
int a; // a is an instance variable
static int b; // b is a static (class) variable
void display(){
int c; // c is a local variable
}
}
class Second{
public static void mian(){
First obj = new First();
obj.a = 10; // to access instance variable we need object of the class
obj.b = 20; // class variable can also be accessed using the object
// First.a = 10; //It won't work as a is instance variable and can be accessed by object only
// First.b = 20; // We can also access static variables by class name directly without using any object
// obj.c = 30; // It won't work. As c is a local variable of method display and can be used only inside that method.
// First.c = 30; //It also won't work as c can only be used inside the method where it is declared.
}
}
So finally I got how we could access an variable in another class without creating an object provided both classes rest in the same package.Just make the variable static.
Here's the code:
import java.io.*;
class A
{
static int a=5;
public void turn()
{
System.out.println("value of a is"+a);
}
}
class B
{
public static void main(String args[])
{
int b;
b=A.a;
System.out.println("value of a is"+b);
}
}
This shows that classes residing in the same package can access each other's members provided it is static even though it is not public because default package access comes to play.
Default access modifier means we do not explicitly declare an access modifier for a class, field,
method, etc.
A variable or method declared without any access control modifier is available to any other
class in the same package. The fields in an interface are implicitly public static final and
the methods in an interface are by default public.
In your class B, a is not defined.
class B {
public void greet() {
System.out.println("Value of a is" + a );//cannot find `a` inside `B`
}
}
Now coming to accessibility, since your both classes are in same package B class can access public, protected and default(no access modifiers) members of other class like A. But in your case a is a local variable inside the A member method value(), so a variable cannot be accessed outside the method where it was declared.
class A {
public static void value() {
int a;//not accessible outside this method
a=5;
}
public static void main() {//FYI: this main is not valid to execute your code, missing here: `String[] args` argument
value();
//`a`, is even not accessible here, forget about class `B`
}
}
Sample code, all are in same package:
class A {
String bar;
}
class B {
public foo() {
A a = new A();//required, as `bar` is instance(non-static) member of class `A`
a.bar 'hi there';//set value
System.out.printf("a.bar = %s\n", a.bar);
}
}
EDIT
Sample code with nested class:
class A {
int foo;
class B {
void setFoo() {
foo = 45; //accessing member of class `A`
}
}
}
Working code:
<pre>
<code>
class A {
private int foo;
private B b;
A() {
foo = -1;
b = new B();
}
class B {
void setFoo(int foo) {
System.out.printf("Inside B's setFoo(), foo = %d\n", foo);
A.this.foo = foo; //accessing member of class `A`
}
}
int getFoo() {
return foo;
}
public void setFoo(int foo) {
System.out.printf("Inside A's setFoo(), foo = %d\n", foo);
b.setFoo(foo);
}
}
class Ideone{
public static void main (String[] args) {
A a = new A();
System.out.printf("main(), foo = %d\n", a.getFoo());
a.setFoo(34);
System.out.printf("main(), foo = %d\n", a.getFoo());
}
}
</code>
</pre>
I have a question about this code right here
public Car {
public static void m1(){
System.out.println("a");
}
public void m2(){
System.out.println("b");
}
}
class Mini extends Car {
public static void m1() {
System.out.println("c");
}
public void m2(){
System.out.println("d");
}
public static void main(String args[]) {
Car c = new Mini();
c.m1();
c.m2();
}
}
I know that polymorphism does not work with static methods, only to instance methods. And also that overriding doesn't work for static methods.
Therefore I think that this program should print out: c, d
Because c calls the m1 method, but it's static, so it can't override and it calls the method in class Mini instead of Car.
Is this correct?
However, my textbook says that the answer should be : a, d
is it a typo? Because I'm a little confused right now.
Please clear this up, thanks.
Because c calls the m1 method, but it's static, so it can't override and it calls the method in class Mini instead of Car.
That's exactly backwards.
c is declared as Car, so static method calls made through c will call methods defined by Car.
The compiler compiles c.m1() directly to Car.m1(), without being aware that c actually holds a Mini.
This is why you should never call static methods through instance like that.
I faced the same issue while working with Inheritance. What I have learned is if the method being called is Static then it will be called from the class to which the reference variable belongs and not from the class by which it is instantiated.
public class ParentExamp
{
public static void Displayer()
{
System.out.println("This is the display of the PARENT class");
}
}
class ChildExamp extends ParentExamp
{
public static void main(String[] args)
{
ParentExamp a = new ParentExamp();
ParentExamp b = new ChildExamp();
ChildExamp c = new ChildExamp();
a.Displayer(); //Works exactly like ParentExamp.Displayer() and Will
call the Displayer method of the ParentExamp Class
b.Displayer();//Works exactly like ParentExamp.Displayer() and Will
call the Displayer method of the ParentExamp Class
c.Displayer();//Works exactly like ChildExamp.Displayer() and Will
call the Displayer method of the ChildtExamp Class
}
public static void Displayer()
{
System.out.println("This is the display of the CHILD class");
}
}
Can private methods be overridden in Java?
If no, then how does the following code work?
class Base{
private void func(){
System.out.println("In Base Class func method !!");
};
}
class Derived extends Base{
public void func(){ // Is this a Method Overriding..????
System.out.println("In Derived Class func method");
}
}
class InheritDemo{
public static void main(String [] args){
Derived d = new Derived();
d.func();
}
}
No, you are not overriding it. You can check by trying to mark it with #Override, or by trying to make a call to super.func();. Both won't work; they throw compiler errors.
Furthermore, check this out:
class Base {
private void func(){
System.out.println("In base func method");
};
public void func2() {
System.out.println("func2");
func();
}
}
class Derived extends Base {
public void func(){ // Is this an overriding method?
System.out.println("In Derived Class func method");
}
}
class InheritDemo {
public static void main(String [] args) {
Derived D = new Derived();
D.func2();
}
}
It will print:
func2
In base func method
When you change func() in Base to public, then it will be an override, and the output will change to:
func2
In Derived Class func method
No, a private method cannot be overridden because the subclass doesn't inherit its parent's private members. You have declared a new method for your subclass that has no relation to the superclass method. One way to look at it is to ask yourself whether it would be legal to write super.func() in the Derived class. There is no way an overriding method would be banned from accessing the method it is overriding, but this would precisely be the case here.
No, it is not. You can mark an override just to make sure like this:
#Override
public void func(){
System.out.println("In Derived Class func method");
}
And in this case it would be a compiler error.
You are not overriding. You cannot override private members, you are merely defining a new method in Derived. Derived has no knowledge Base's implementation of func() since its declared as private. You won't get a compiler error when you define func() in Derived but that is because Derived does not know Base has an implementation of func(). To be clear: it would be incorrect to say you are overriding Base's implementation of func().
In addition to the already correct answer, consider this:
public class Private {
static class A {
public void doStuff() {
System.out.println(getStuff());
}
private String getStuff() {
return "A";
}
}
static class B extends A {
public String getStuff() {
return "B";
}
}
public static void main(String[] args) {
A a = new A();
a.doStuff();
a = new B();
a.doStuff();
B b = new B();
b.doStuff();
}
}
This will print
A
A
A
although B "overrides" getStuff(). As implementation of doStuff() is fixed to calling A#getStuff(), no polymorphism will be triggered.
Nope because if you do something like Base b = new Derived(); you still won't be able to call b.func(). What you're doing is called "hiding".
Since the method is private it is not visible to the other classes.Hence the derived class does not inherit this method.
So this is not the case of overriding
Method hiding will be happening here instead of overriding. like what happens in case of static.
Actually,you are not overriding.Before Java5
an overridden method's return type must match with parent class's method.
But Java 5 introduced a new facility called covariant return type.You can override a method with the same signature but returns a subclass of the object returned. In another words, a method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the superclass.
you can follow this thread :Can overridden methods differ in return type?
The private member of the base class cannot be access by anyone outside of the class and cannot be overridden. The function in the derive class is an independent function that can be access by anywhere.
The code would run the function in the derived class
A private method can never be over ridden. It is always hidden.
In your example - Derived class has one parent class private method and has its own function func. Both are different, and the func is not over ridden. Its a separate independent function.
If you create a new function in parent class calling parent class function, the parent func will be called, if parent class reference is used as opposed in the case of method over ridding
Note : An object defines the members which it has, and a reference defines which it can access
// Method Over ridding case
class Base{
public void func(){
System.out.println("Parent class");
};
public void func1(){
func();
}
}
class Derived extends Base{
public void func(){
System.out.println("Derived class");
}
}
class InheritDemo{
public static void main(String [] args){
Derived d = new Derived();
d.func1(); // Prints Derived class
Base b = new Derived();
b.func1(); // Prints Derived class - no matter parent reference is calling,as there as method is overridden - Check func1() is in parent class, but id doesn't call parent class func() as the compiler finds a func() method over ridden in derived class
}
}
// Method Hidding case - Private and static methods case
class Base{
private void func(){
System.out.println("Parent class");
};
public void func1(){
func()
}
}
class Derived extends Base{
public void func(){ // Is this a Method Overriding..????
System.out.println("Derived class");
}
}
class InheritDemo{
public static void main(String [] args){
Derived d = new Derived();
d.func1(); // Prints Derived class
Base b = new Derived();
b.func1();
// Prints Parent class - the reason is we are using the parent class reference, so compiler is looking for func() and it founds that there is one private class method which is available and is not over ridden, so it will call it. Caution - this won't happen if called using derived class reference.
b.func();
// this prints the Derived class - the compiler is looking func(), as Derived class has only one func() that it is implementing, so it will call that function.
}
}
Read comments in the below code snippet to find the answer.
Sources:
Definition reference:
Credits for the source code example(reference) from the book - "OCA Oracle Certified Associate Java SE 8 Programmer Study Guide Exam 1Z0-808 Book" from 'Jeanne Boyarsky' and 'Scott Selikoff'.
public class Deer {
public Deer() { System.out.print("Deer"); }
public Deer(int age) { System.out.print("DeerAge"); }
private boolean hasHorns() { return false; }
public static void main(String[] args) {
Deer deer = new Reindeer(5);
System.out.println(","+deer.hasHorns());// false is printed.
}
}
class Reindeer extends Deer {
public Reindeer(int age) { System.out.print("Reindeer"); }
private boolean hasHorns() { return true; } // Overriding possible, but is of no use in the below context.
// Below code is added by me for illustration purpose
public static void main(String[] args) {
Deer deer = new Reindeer(5);
//Below line gives compilation error.
//System.out.println(","+deer.hasHorns());
}
}