Accessing value with same name in interface and abstract class-Java - java

I have abstract class and interface like this
abstract class ParentClass
{
int VALUE;
public abstract void display();
public void display2()
{
System.out.println("this is abstract class method");
}
}
interface parentInterface
{
int VALUE=88;
abstract void display();
void display2();
}
the child class extends and implements the above like following
class ChildClass extends ParentClass implements parentInterface
{
ChildClass()
{
super.VALUE=0;
//VALUE=0; //<=will give ambiguous property
}
#Override
public void display()
{
System.out.println("Current Class-"+this.getClass());
System.out.println("Integer value-"+super.VALUE);
}
public void display2()
{
//to call the method of abstract class
//call by using super.display2();
System.out.println("this is implemented method");
}
}
So, my question is How can i access interface VALUE variable in ChildClass ??

You can access the VALUE from interface using parentInterface.VALUE as variables in interfaces are public static final by default.
And the abstract class's VALUE can be accessed using this.VALUE as it is a member variable.

variables in interface are implicitly public static final.
static - because Interface cannot have any instance.
final - the value assigned to the interface variable is a true constant that cannot be re-assigned by program code.
Interface variables can be accessed using <Interface>.VALUE whereas the variables from the parent class are inherited and hence can be accessed using this.VALUE.
if any subclass class is implementing an interface which has instance
members and if both subclass and interface are in the same package
then that static members can be accessed from the child class without
even using the Interface name.
Thats why you are getting the ambiguous error. Please put Interface in some other package and then it should not show such an error else you will have to access it like super.VALUE

Related

Learning a little about using interface variable

I recently saw implementing where a interface is implemented in a class and in another class we have a static final variable of the interface type and it somehow was able to complete computation from the class that had implemented the interface .
My question is how will the interface variable handle this if more than one class has a implementation of the interface. Am I missing something or it is just guessing where the implementation of interface is .
This is for java language
public interface DemoMe{
public void doSomething();
}
public class MainClass implements demoMe {
public void doSomething(){
System.out.println("Something was done ");
}
}
public class AnotherClass {
private final DemoMe demoVariable;
public void useMe(){
demoVariable.doSomething();
}
}
here the AnotherClass somehow knows how to look for implementation of doSomething. can someone point me towards how this exactly works.
The variables in java interface are public static and final type. You whenever a class implements an interface. The interface variable become part of the class. Now these variable can be accessed using class reference or object reference. These variable are final so cannot be updated and static so always belong to the class. The interface itself need not to manage anything. The implementing class will take care of it.
Here we have defined an interface DemoMe with one method and one variable. Now DemoMeOne class implements the interface. The need to provide the definition for methods coming from interface. The doSomething() method simply prints a statement an access the variable from interface. Now we define an other class which instantiate the DemoMeOne class and access the interface method and variable.
interface DemoMe{
public void doSomething();
public int variable = 100;
}
class DemoMeOne implements DemoMe {
public void doSomething(){
System.out.println("Something was done.");
System.out.println("Access interface variable: " + variable);
}
}
class MainClass {
public static void main(String[] args) {
DemoMeOne demoMeOne = new DemoMeOne();
System.out.println("Variable from interface using DemoMeOnce class: " + DemoMeOne.variable);
System.out.println("Variable from interface using DemoMeOnce object reference: " + demoMeOne.variable);
System.out.println("Variable from interface using interface itself: " + DemoMe.variable);
demoMeOne.doSomething();
}
}
output:
Variable from interface using DemoMeOnce class: 100
Variable from interface using DemoMeOnce object reference: 100
Variable from interface using interface itself: 100
Something was done.
Access interface variable: 100

What is the difference between a public and private interface in Java

I know the difference between all the access modifiers in Java. However, someone asked me a very interesting question that I struggled to find the answer to: What is the difference between a private interface and a public interface in Java, in particular, how it is used as a class member? Any help would be greatly appreciated.
I believe we all know the use of public interface, so I would mention the point of private/protected interface here.
Interfaces can be members of class definitions and can be declared private or protected there.
public class Test {
private interface Sortable {
}
protected interface Searchable {
}
}
Example 1: -- Source
public class PrivateInterface {
private interface InnerInterface {
void f();
}
private class InnerClass1 implements InnerInterface {
public void f() {
System.out.println("From InnerClass1");
}
}
private class InnerClass2 implements InnerInterface {
public void f() {
System.out.println("From InnerClass2");
}
}
public static void main(String[] args) {
PrivateInterface pi = new PrivateInterface();
pi.new InnerClass1().f();
pi.new InnerClass2().f();
}
}
/* Output:
From InnerClass1
From InnerClass2
*/
It's the interface itself that can be package-private, not the methods
in it. You can define an interface that can only be used (by name)
within the package it's defined in, but its methods are public like
all interface methods. If a class implements that interface, the
methods it defines must be public. The key thing here is that it's the
interface type that isn't visible outside the package, not the
methods.
The public, private, and protected access modifiers on an interface mean the same thing that they mean on a class. I typically see these modifiers used on an interface that is nested in a class. Something like this:
//: interfaces/RandomWords.java
// Implementing an interface to conform to a method.
package interfaces;
public class PrivateInterface {
private interface InnerInterface {
void f();
}
private class InnerClass1 implements InnerInterface {
public void f() {
System.out.println("From InnerClass1");
}
}
private class InnerClass2 implements InnerInterface {
public void f() {
System.out.println("From InnerClass2");
}
}
public static void main(String[] args) {
PrivateInterface pi = new PrivateInterface();
pi.new InnerClass1().f();
pi.new InnerClass2().f();
}
}
An interface declaration may include these access modifiers:
public protected private abstract static strictfp
public: If an interface type is declared public,then it can be accessed by any code.
protected/private: The access modifiers protected and private pertain only to member interfaces within a directly enclosing class declaration. A member interface is an interface whose declaration is directly enclosed in another class or interface declaration.
static: The access modifier static pertains only to member interfaces, not to top level interfaces.
abstract: Every interface is implicitly abstract. This modifier is obsolete and should not
be used in new programs.
strictfp: The effect of the strictfp modifier is to make all float or double expressions
within the interface declaration be explicitly FP-strict.
Ref: Java Language and Virtual Machine Specifications

Why the answer will be "GOOD"?

Following is the code I tried to run, the output was Good. So, we can use a variable of interface implemented by a class?
interface IDummyInterface {
public String TYPE = "Good";
}
class Test implements IDummyInterface {
}
public class MyApplication {
public static void main(String[] args) {
System.out.println(Test.TYPE);
}
}
Any class that implements an interface, and any class that extends a class that implements that interface, inherits all of that interfaces variables. No matter how you declare the variables in the interface, all interface variables are public static final, which is why you can access them with just the class name and not an instance of the class.
Test implements IDummyInterface.so all variables of IDummyInterface are inherited
The variable is actually static final. And since it is static, it follows the same rules as all static variables declared in classes, which are accessible through any other class that inherit from it. In that regard interfaces behave like classes.
class StaticTestParent { public static final int VALUE = 1; }
class StaticTestChild extends StaticTestParent { }
static {
System.out.println(StaticTestChild.VALUE);
}

Inner classes inside Interface

Can we have a class inside an interface which has different methods of the interface implemented in it. I have a doubt here that why Java allows writing Inner classes inside interfaces and where can we use it.
In the program below I have written a class inside Interface and implemented the methods of the interface. In the implementation class of the interface I have just called the inner class methods.
public interface StrangeInterface
{
int a=10;int b=5;
void add();
void sub();
class Inner
{
void add()
{
int c=a+b;
System.out.println("After Addition:"+c);
}
void sub()
{
int c=a-b;
System.out.println("After Subtraction:"+c);
}
}
}
abstract public class StrangeInterfaceImpl implements I {
public static void main(String args[])
{
StrangInterface.Inner i=new StrangeInterface.Inner();
i.add();
i.sub();
}
}
You can define a class inside an interface. Inside the interface, the inner class is implicitly public static.
From JLS Section 9.1.4:
The body of an interface may declare members of the interface, that is, fields (§9.3), methods (§9.4), classes (§9.5), and interfaces (§9.5).
From JLS Section 9.5:
Interfaces may contain member type declarations (§8.5).
A member type declaration in an interface is implicitly static and public. It is permitted to redundantly specify either or both of these modifiers.
The only restriction on the inner class defined inside the interface or any other class, for that matter, is that, you have to access them using the enclosing member name.
Apart from that, there is no relation between them. The inner class will result in completely a different class file after compilation.
For e.g., if you compile the following source file:
interface Hello {
class HelloInner {
}
}
Two class files will be generated:
Hello.class
Hello$HelloInner.class
Can we have a class inside an interface which has different methods of the interface implemented in it.
IMHO But interfaces are not meant to for that purpose.
If you write inner class in an interface it is always public and static.
It's equivalent to
public interface StrangeInterface
{
public static class Inner{
}
and the variable inside the interface also explicitly public static variables.
An interface might provide its own implementation as a default.
Note that unless you declare the inner class implements the interface, there's no relation between the two other than it's an inner class. When a class is very tightly related to the interface this isn't intrinsically unreasonable, although I'd be suspicious it's a generally-useful pattern.
to summarize "where can we use it" by defining a class inside an interface:
1. to provide default implementation for an interface
2. if argument or return type for interface method/s is class
w.r.t your code
interface StrangeInterface {
int a = 10;
int b = 5;
void add();
void sub();
class Inner implements StrangeInterface {
public void add() {
int c = a + b;
System.out.println("After Addition:" + c);
}
public void sub() {
int c = a - b;
System.out.println("After Subtraction:" + c);
}
}
}
class MyTest implements StrangeInterface {
public void add() {
System.out.println("My own implementation for add : " + (a +b));
}
public void sub() {
System.out.println("My own implementation for sub : " + (a- b));
}
}
public class StrangeInterfaceImpl {
public static void main(String args[]) {
StrangeInterface.Inner i = new StrangeInterface.Inner(); // calling default implementation
i.add();
i.sub();
MyTest t = new MyTest(); // my own implementation
t.add();
t.sub();
}
}

Java abstract class fields override

I have an abstract class that should implement a public field, this field is an interface or another abstract classe.
something like this:
public abstract class GenericContainer {
public GenericChild child;
}
public abstract class GenericChild {
public int prop1=1;
}
public abstract class SpecialChild extends GenericChild {
public int prop1=2;
}
Now i have another specialized class Container:
public abstract class SpecialContainer extends GenericContainer {
public SpecialChild child=new SpecialChild(); //PAY ATTENTION HERE!
}
Java allow me to compile this, and i IMAGINE that the field child in SpecialContainer is automatically overloading the field child of the GenericContainer...
The questions are:
Am i right on this? The automatic 'overloading' of child will happen?
And, more important question, if i have another class like this:
public class ExternalClass {
public GenericContainer container=new SpecialContainer();
public int test() {
return container.child.prop1
}
}
test() will return 1 or 2? i mean the GenericContainer container field what prop1 will call, the generic or the special?
And what if the special prop1 was declared as String (yes java allow me to compile also in this case)?
Thanks!
In Java, data members/attributes are not polymorphic. Overloading means that a field will have a different value depending from which class it's accessed. The field in the subclass will hide the field in the super-class, but both exists. The fields are invoked based on reference types, while methods are used of actual object. You can try it yourself.
It's called, variable hiding/shadowing, for more details look on here
It isn't overriding anything, you're just hiding the original field at the current class scope. If you use a variable with the subtype you will still be able to access the original property. Example:
abstract class GenericContainer {
public GenericChild child;
}
abstract class GenericChild {
public int prop1=1 ;
}
class SpecialChild extends GenericChild {
public int prop1=2;
}
class SpecialContainer extends GenericContainer {
public SpecialChild child;
}
public class Main {
public static void main( String ... args ) {
GenericContainer container = new SpecialContainer();
container.child = new SpecialChild();
System.out.println( container.child.prop1 );
SpecialChild child = (SpecialChild) container.child;
System.out.println( child.prop1 );
}
}
This prints 1 and then 2.
From SpecialChild you would also be able to go up one level using super:
class SpecialChild extends GenericChild {
public int prop1=2;
public int getOriginalProp1() {
return super.prop1;
}
}
Regarding
....and i IMAGINE that the field "child" in SpecialContainer is automatically overloading the field 'child' of the GenericContainer...
No. Fields don't get overridden, only methods do.
This is one reason why use of (overridable) getter and setter methods are preferred to direct access to fields. Your fields should almost all be private.
As for your design, there's no need for your SpecialContainer class to have a SpecialChild field, but instead the SpecialChild object should be placed in the GenericChild field.
Why nobody is observing that program will throw NullPointerException.
subclass's field with same name will hide super class's field. There is no overriding with field. Overriding is only possible with methods.
Original Code by Author:
public abstract class GenericContainer {
public GenericChild child;
}
public abstract class GenericChild {
public int prop1=1;
}
public abstract class SpecialChild extend GenericChild {
public int prop1=2;
}
public abstract class SpecialContainer extends GenericContainer {
public SpecialChild child=new SpecialChild(); //PAY ATTENTION HERE!
}
public class ExternalClass {
public GenericContainer container=new SpecialContainer();
public int test() {
return container.child.prop1
}
}
Java allow me to compile this, and i IMAGINE that the field "child" in
SpecialContainer is automatically overloading the field 'child' of the
GenericContainer...
Firstly, Inheritence doesn't apply to variables. Fields(Insatnce variables) are not overridden in your sub-class.they are only visible in your subclass if they are marked with either public, protected or default.
To answer your question it maintains both instances. And depending on how you refer to the container (either through the abstract or the impl) determines which variable you are referring to.
public class Test {
public abstract class Container{
public Generic gen = new Generic();
}
public class ContainerImpl extends Container{
public GenericImpl gen = new GenericImpl();
}
public class Generic{
public int prop = 0;
}
public class GenericImpl extends Generic{
public int prop = 1;
}
public Test(){
Container c = new ContainerImpl();
System.out.println(c.gen.prop); // Outputs "0"
System.out.println(((ContainerImpl)c).gen.prop); // Output "1"
}
public static void main(String[] args) {
new Test();
}
}
The bigger question at hand is, why would you design something like this? I'm assuming you are asking from a theoretical perspective.
My 2 cents, this isn't great OO design. You would be better off making the public variables private and assigning their values through a constructor or property setter. As-is, it will lead to unexpected results in your code.

Categories

Resources