Why does class ref type and interface ref type have a different access scope of their methods.
In the following example
interface ImInterface{
void do1();
void do2();
}
class MyClass implements ImInterface {
void do1(){
System.out.println("do1");
}
void do2(){
System.out.println("do2");
}
void do3(){
System.out.println("do3");
}
}
Could you help me understand why mc variable defined like
MyClass mc = new MyClass();
cannot access do1 and d2 without any cast? It implements all functionality from contract (ImInterface). Why is it like this in Java?
Also, why mi defined like
MyInterface mi = new MyClass();
cannot access do3 without any cast?
I know both mi and mc have different types, but after implementations both become one now, then why it's a difference to access without cast? mc and mi both point to same type of instance.
Since you are declaring the object mi as of type MyInterface, you will only have access to the methods that are declared on MyInterface.
When you declare the object mc as of type MyClass, you will have access to all the methods declared in MyClass and its superclass.
When Java looks at the reference mi, it will just know that it is of type MyInterface.
Now if you declared mc outside of the package then you won't be able to access any of their methods because they have package visibility.
Why mc cannot access do1 and d2 without any cast ?
It can, provided you call mc.do1() or mc.do2() from a class within the same package where MyClass is declared. In Java, when you don't declare an access modifier for a method or a field, Java allows it to be accessible only within the same 'package' where the class is declared. For do1() and do2() to be accessible anywhere, declare them with a public 'modifier':
public void do1() {
...
}
Note: This is not applicable for interfaces as all methods in interfaces are by default 'public', even when the keyword is not specified.
Why mi cannot access do3 without any cast ?
That's how Java is designed. An interface specifies a contract (what, and not, how). So when a class implements an interface, it has to adhere to that contract, plus it can declare it's own functionalities. But as long as you refer to the object of the implementation class with the reference of the interface:
MyInterface mi = new MyClass();
the interface reference will be able to access only the method it has declared. In other words, the interface reference can only tell what it 'knows for sure' to be present in the implementation (as the implementation class has implemented the interface) and not the other functionalities (methods) of the implementation class.
Methods of an interface are implicitly public and methods of a class with no specified access modifier have weaker access privileges than public.
When you implement an interface's method, the implementing class cannot have weaker access modifier for it than specified in the interface.
In your example you are trying to implement an interface with implicitly public methods through methods that have no modifier, violating the rule above. If you want to make this code work, you should make these methods explicitly public.
mi cannot access do3() because it has no information about this method in ImInterface declaration (and mis type is ImInterface). This is the reason you have to explicitly cast mi to MyClass, telling Java that it can treat this object in by more "narrow" means.
You can find more information about interfaces here.
Related
All classes in java extend the Object class implicitly. But that doesn't concern interfaces. Interfaces can only extend other interfaces, but no classes. However, I can override object class methods inside my interface.
public interface NewInterface {
#Override
boolean equals(Object var1);
#Override
int hashCode();
}
Can you please explain in simple words how is this even possible? Is there any use case for this?
Interface is a just contract. It says that all classes that inherits interface should implement these methods. Interface cannot have implementation. It is possible to override a class that implements this interface.
However, from Java 8 you can define static methods in interfaces in addition to default methods.
UPDATE:
The members of an interface are:
Those members declared in the interface.
Those members inherited from direct superinterfaces.
If an interface has no direct superinterfaces, then the interface implicitly declares a public abstract member method corresponding to each public instance method declared in Object, . It is a compile-time error if the interface explicitly declares such a method m in the case where m is declared to be final in Object.
Now it is clear that all superinterface have abstract member method corresponding to each public instance method declared in Object .
Read more about interface members here
You cannot declare an interface inside a block like below
public void greetInEnglish() {
interface HelloThere {
public void greet();
}
class EnglishHelloThere implements HelloThere {
public void greet() {
System.out.println("Hello " + name);
}
}
HelloThere myGreeting = new EnglishHelloThere();
myGreeting.greet();
}
In This Oracle tutorial I got "You cannot declare member interfaces in a local class." because "interfaces are inherently static."
I am eagar to understand this with more rational information, why and how interface are inherently static?
and why above code does not make sense?
Thanks in advance to elloborate!
I am eagar to understand this with more rational information, why and
how interface are inherently static?
because interfaces are implicitly static, and you can't have non-final statics in an inner class.
Why are they implicitly static?
because that's the way they designed it.
and why above code does not make sense?
because of the above reason ,
Now lets make it simple :
What static means - "not related to a particular instance". So, suppose, a static field of class Foo is a field that does not belong to any Foo instance, but rather belongs to the Foo class itself.
Now think about what an interface is - it's a contract, a list of methods that classes which implement it promise to provide. Another way of thinking about this is that an interface is a set of methods that is "not related to a particular class" - any class can implement it, as long as it provides those methods.
So, if an interface is not related to any particular class, clearly one could not be related to an instance of a class - right?
I also suggest you to study Why static can't be local in Java?
Any implementations can change value of fields if they are not defined as final. Then they would become a part of the implementation.An interface is a pure specification without any implementation.
If they are static, then they belong to the interface, and not the object, nor the run-time type of the object.
An interface provide a way for the client to interact with the object. If variables were not public, the clients would not have access to them.
Your code does not make sense because you define the interface within the body of a method. You can define an interface either at top level or in another class or interface.
You cannot declare an interface inside a block
reference
Just had this in a unit test. So:
abstract class A {...}
class B extends A {...}
A a = new B();
Pretty much doubt it's viable, but I'm totally confused at the moment. The content of the classes is irrelevant.
yes this concept is known as polymorphism in java . a parent can contains reference of child class. and parent can be either interface or abstruct class. even you need not to cast . for example .
a animal can be horse or cat , here animal is an interface or abstract class.
i recommend (SCJP Sun Certified Programmer -kathy sierra)book has lot of concepts related to java language.
Its valid in java. this is called implicit up casting (JVM casts sub type to super type object) where reference of super type can refer to sub type but with super type reference you can only get access to only those variables and methods which are declared/defined in super type.
Yes this is valid in java
abstract class A {...}
class B extends A {...}
A a = new B();
Yes this is a valid java assignment statement.
A a = (A) new B();
In java a child object can be referenced from the parent class.
It's valid.
As per Java's fundamental rule "Super class reference (A a) can refer sub class object (b= new B())".
Interface - every method is always public and abstract whether you are declaring it or not. You can’t declare an interface method with the following modifiers. Every variable present inside interface is always public static and final whether we are declaring or not. You can’t declare an interface variable with the following modifiers, private, protected, transient and volatile. The variables present within abstract class don’t have to be public, static and final. There are no restrictions on abstract class variable modifiers. For abstract class variable are not required to perform initialization at the time of declaration. An abstract class can declare instance and static blocks. Inside interface we can’t declare instance and static blocks otherwise we will get compile time error. Interface can’t declare constructors. Just keep these fun facts in mind.
I've been wondering why it's allowed to do a code implementation in an interface, when interfaces are suppossed to contain no code implementation:
public interface someInterface{
String someString = "example";
}
I can make a class implement this interface, without getting an error:
public class someClass implements someInterface
How come?
You are allowed to declare constants in interfaces, which is what you have done. You have not implemented code.
Variables declared in interfaces are implicitly declared public static final.
The JLS, Section 9.3, covers this:
Every field declaration in the body of an interface is implicitly
public, static, and final. It is permitted to redundantly specify any
or all of these modifiers for such fields.
According to java docs
Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.
Here you are not defined any methods to implement.So you didn't get any error here.
There is no strict condition that an interface must have signatured methods.Remember there are Marker Interfaces too in java.
And secondly , You can declare variables inside interface.
And that variable someString assigned in a static context and shared across all the implemntations by that interface
Point is that the variables inside declared interface are implicitly static and final.You can use them.
As you know, in a java interface, all methods have to be defined as abstract. But when I define a method as not typing abstract, the compiler says it is okay. I know that an abstract method must not have a body. Does a method somewhere in an interface necessarily have a name abstract or not? : What i mean is, what is the difference between:
public interface blabla {
public void aMethod();
//or
public abstract void aMethod();
}
No, marking an interface method as abstract has no meaning and is never required.
All interface methods are implicitly abstract (and public too btw).
From the JLS:
Every method declaration in the body of an interface is implicitly abstract, so its body is always represented by a semicolon, not a block.
Every method declaration in the body of an interface is implicitly public.
For compatibility with older versions of the Java platform, it is permitted but discouraged, as a matter of style, to redundantly specify the abstract modifier for methods declared in interfaces.
It is permitted, but strongly discouraged as a matter of style, to redundantly specify the public modifier for interface methods.
Related question (+ answer with a historical reference to a statement saying that abstract was once required for interface methods):
Java abstract interface
See the sample example below
interface xyz
{
void methodA();
}
Save this to xyz.java
Now compile this using javac tool
and then use the command given belo
javap xyz
the output would be
Compiled from "xyz.java"
interface xyz {
public abstract void methodA();
}
That means when you compile an interface, compiler makes its signature to public and abstract by default.
So it is not necessary to use abstract keyword for any method of interface.
I don't know that they have to be defined as abstract. Probably because they don't. See Oracle's tutorial.
you don't need to specify abstract (default) because within an interface it does not make sense as all the method of the interface needs to be implemented
All methods in an interface are abstract by definition.
You can't create an object out of an interface (e.g., using Interface i = new Interface();) so there's no difference between marking a method as abstract or not.
Any class that implements the interface needs to decide whether to implement it or to let a subclass do it. So as far as the interface is concerned, all methods are abstract by default.
An abstract method provides no implementation. A class which has an abstract method is necessarily abstract, which means that you cannot create instances of this class. To create an instance of that class, you need to subclass and provide non-abstract overwrites for the abstract methods.
An interface never provides an implementation of its methods and it cannot be instantiated. Therefore every method of an interface is per definition abstract. You do not need to provide the keyword abstract when declaring a method in an interface. And by convention the keyword abstract is not used within an interface.
The methods of an interface don't have to be explicitly defined as abstract because they are implicitly abstract and public as defined in the Java Language Specification §9.4. A redundant declaration is perfectly legal though.
If you forgot to put abstract keyword before interface method, Java will implicitly put public abstract keyword before it. Because all interface methods must be abstract.