Inheritance with a variable in java - java

Can anyone clarify me. Here instance method is overridden but variable is not.
output is: B 10
class A{
int i=10;
public void name(){
System.out.println("A");
}
}
class B extends A{
int i=20;
public void name(){
System.out.println("B");
}
}
public class HelloWorld {
public static void main(String[] args){
A a = new B();
a.name();
System.out.println(a.i);
}
}

You are absolutely correct. Methods are overridden in Java if the parameter list and function names are identical, and the return types are covariant.
i in the base class is simply shadowed: a.i refers to the i member in the base class, since the type of the reference a is an A, even though it refers to a B instance.

You cannot override attribute, you can only override method:
public class A{
private int i=10;
public void name(){
System.out.println("A");
}
public int getI(){
return i;
}
}
public class B extends A{
private int i=20;
public void name(){
System.out.println("B");
}
#Override
public int getI(){
return i;
}
}
public class HelloWorld {
public static void main(String[] args){
A a = new B();
a.name();
System.out.println(a.getI());
}
}
In your example, you define variable a as type A so the i value in B is ignored.

In Java instance variables cannot be overridden, only methods can be overridden. When we declare a field with same name as declared in super class then this new field hides the existing field. See this Java doc Hiding Fields.

Related

implementing static methods for interface

suppose I have an interface:
public interface abcd{
public int a();
public void b();
public void c();
public String d(String h, String j);
}
and I implement it in some class:
public class xyzw implements abcd{
}
but I want the method d() to be static, but I can't do this:
public class xyzw implements abcd{
public static void c(){
//some code
}
}
neither can I do this:
public interface abcd{
public int a();
public void b();
public static void c();
public String d(String h, String j);
}
I wonder if there is something or some workaround or some language construct which allows me to make a method defined by an interface a static method?
You can define a static method in interface, but only with implementation.
public interface A {
public static void b() {
System.out.println("Hi");
}
}
Overriding of static methods is not allowed in Java, because you call it on Class object, not on implementation object.
If you can implement a static method in an interface, but you cannot overwrite it, remember that a static method is referenced by the class itself and not by an instance of it.
To solve your problem maybe you could define an abstract class
No, its not possible and doesn't make any sense. An interface is meant to be implemented by subclasses you can only hava a non-abstract, implemented, static method in an interface. You could not statically call your interface method with
abcd.c()
when it has no implementation. Thats why static elements can not be overridden.
It's not possible to override static methods in java.
However, in the subclass, you can declare static method with the same name and "mask it as" the original method - which is as close as you can get.
interface a {
public static int f() {
return 0;
}
}
interface b extends a {
public static int f() {
return 1;
}
}
System.out.println(a.f());
>> 0
System.out.println(b.f());
>> 1

Property with same name in Child class java

public class HelloWorld
{
protected int num = 12;
public void callme()
{
System.out.print(this.num);
}
public static void main(String[] args)
{
HelloWorld myObject1 = new HelloWorld();
myObject1.callme();
OtherClass myObject2 = new OtherClass();
myObject2.callme();
}
}
public class OtherClass extends HelloWorld
{
protected int num = 14;
}
Why the output is "1212" instead of "1214"? In php its "1214" but not viceversa in java. What's the logic behind that?
callme() method is defined only in the base class, and therefore return this.num; returns the instance variable of the base class.
There is no overriding of instance variables in Java.
If you'd override that method in the sub-class, by adding
public void callme()
{
System.out.print(this.num);
}
to OtherClass, myObject2.callme(); will return 14, since it will execute callme() method of the sub-class, and therefore access the sub-class instance variable.

How is it possible to access the instance variable of aa abstract class to a class?

How can I use this abstract class instance variable in my DemoAbs class?
This is the D class:
abstract class D {
int i=10;
String str="java";
D(){
System.out.println("called abstract class constructor");
}
abstract void m1();
void m2() {
int i=20;
System.out.println("called m2() in abstract class !");
}
}
This is the DemoAbs class:
public class DemoAbs extends D{
// access instance variable here from abstract class
DemoAbs() {
System.out.println("called DemoAbs class constr");
}
#Override
void m1() {
System.out.println("inside m1() method");
}
public static void main(String[] args) {
DemoAbs d=new DemoAbs();
d.m1();
d.m2();
}
}
accessing instance fields of a superclass from a subclass is simple: just use the name of these instance fields as-is. The only caveat: these fields must have the proper visibility. In your case you define the i field to have default visibility which may not always work[1]. To make sure the field is visible to subclasses it should be defined with the protected visibility.
Here's your program (slightly adapted) that shows this:
abstract class D {
protected int i=10;
protected String str="java";
D(){
System.out.println("called abstract class constructor");
}
protected abstract void m1();
void m2() {
System.out.println("called m2() in abstract class! i=" + i);
}
}
public class DemoAbs extends D{
// access instance variable here from abstract class
DemoAbs() {
System.out.println("called DemoAbs class constr");
}
#Override
protected void m1() {
i = 30;
System.out.println("inside m1() method");
}
public static void main(String[] args) {
DemoAbs d=new DemoAbs();
d.m1(); // Output: "inside m1() method"
d.m2(); // Output: "called m2() in abstract class! i=30"
}
}
Note that the call to d.m2() will produce output which says "i=30". That's because the call to d.m1() carried out the assignment i = 30 (see body of of DemoAbs.m1()) thus changing i from its initial value (10 see its declaration in D).
[1] Specifically, if the subclass is declared in a different package than the superclass, a field with default visibility will not be visible to it.
You can use super keyword to access superclass non private variables from methods of subclass
Your code(modified):
abstract class D {
int i = 10;
String str = "java";
private String newStr = "java not accessible";
D() {
System.out.println("called abstract class construtar");
}
abstract void m1();
void m2() {
int i = 20;
System.out.println("called m2() Abstrate class !");
}
}
public class DemoAbs extends D {
// access instance variable here from abstract class
DemoAbs() {
System.out.println("called DemoAbs class contr");
}
#Override
void m1() {
System.out.println(super.i); // added
System.out.println(super.str); // added
//System.out.println(super.newStr); -- Not accessible
System.out.println("inside m1() method");
}
public static void main(String[] args) {
DemoAbs d = new DemoAbs();
d.m1();
d.m2();
}
}
Simply In your main method just do this,
public static void main(String[] args) {
DemoAbs d=new DemoAbs();
d.m1();
d.m2();
int num = d.i;
String strVar = d.str;
}
Now variable num and strVar are holding the values of the member variable.
You can define getter method for instance variables in abstract class D and access it using DemoAbs class instance.

Can an Interface variable be reinitialised?

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

java, inheritance — private field in parent is accessed through a public method in child

So, one friend sent me this code and said that it had compiled successfully and returned 42.
But, the bothering thing is the method in parent class that "returns" 42 is private, and the method that is called on is in child class, and it's public. So, can anybody tell why and how this works?
static class A {
private int f() {
return 42;
}
}
static class B extends A {
public int f2() {
return super.f();
}
}
public static void main(String[] args) {
System.out.print(new B().f2());
}
It returns 42.
I tried to get rid of static, and
class A {
private int f() {
return 42;
}
}
class B extends A {
public int f2() {
return super.f();
}
}
public static void main(String[] args) {
Main m= new Main();
B b= m.new B();
System.out.print(b.f2());
}
it still returns 42.
Since both of the classes (A and B) are nested in Main, they can access the private int f() method.
If you extract the sources of A and B in top-level classes, this won't happen and you'll fail to compile.
The point of private is that "outside" classes should not be able to see private variables. But A and B are both part of the same class, or are nested within each other, so they can access each others private members.
So this will work:
public class A {
private void a() {
int bVal = this.new B().val; //! Accessing B private
}
class B {
A a = new A();
private int val = 10;
public void b() {
a.a(); // !! Accessing A private
}
}
BUT, this will fail, even if both A and B are in the same file but not within each other:
class A {
private void a() {}
}
class B extends A {
A a = new A();
public void b() {
a.a(); // can't see even if B extends A
}
}
This is because both classes A and B are nested inside another class, i.e both classes are inner classes of (or "part of") another same class. Since they (Data Members and Methods) are basically a member of the outer class,they are accessible within other inner classes even if private.
Java allows us Nesting of classes,If You Don't know about nested classes first read this :
http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
class Outer{
class A {
private int f() {
return 42;
}//Method f() is a private member of A and accessible by Outer
}
class B extends A {
public int f2() {
return super.f();
}//As class B is inner class of Outer it can access members of outer,thus indirectly member of A
}
public static void main(String[] args) {
System.out.print(new B().f2());
}
}

Categories

Resources