I am learning of interface in java while i access it in my sub class main method i can access in three way what are the difference of those am learner could some one help on this
public interface interfa
{
void educationloan();
abstract void homeloan();
static int i = 10;;
}
public class testinter implements interfa {
public static void main(String args[])
{
System.out.println("Sub class access a interface by implement");
testinter t = new testinter();
t.miniloan();
t.educationloan();
t.homeloan();
System.out.println("Super class access a only interface in sub class");
interfa a = new testinter();
a.educationloan();
//a.miniloan();
a.homeloan();
System.out.println("Annomys class access a only interface in sub class");
interfa xx = new interfa() {
#Override
public void homeloan() {
}
#Override
public void educationloan() {
// TODO Auto-generated method stub
}
};
xx.educationloan();
xx.homeloan();
}
}
Here my question comes which one can use in which situation and what are the difference???
First thing you will get a compile time error big time as you haven't implemented the interface methods in the child class.
testinter t = new testinter();
t.miniloan();
t.educationloan(); // these methods should be initialized
t.homeloan();
Now regarding your interface implementation ways:
testinter t = new testinter();
t is an instance of a child class & can be used like a regular class object.
interfa a = new testinter();
The upside of using this approach is say you have used the reference a n times in your code & in future you want to change the implementation of your interface to interfa a = new AnotherTestinter(); All you have to do is change the implementation the reference will not be changed. This is loose coupling otherwise you have to change the reference a everywhere in the code. This approach is always known as Programming to an interface.
Using anonymous class
interfa xx = new interfa() {
#Override
public void homeloan() {
}
#Override
public void educationloan() {
// TODO Auto-generated method stub
}
};
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. Use them if you need to use a local class only once.
So doing this interfa xx = new interfa() { helps you define your methods educationloan() homeloan() at the same place.
t itselft is a instance of a child class. it can be used normally like other class objects
t is a instance of the interfa. Here t can be used in both cases where either the child or the parent class is needed.
in this implementation you have to implement the methods of the interface in your own way. You can implement different things here instead of using the default implementation.
N.B. I overlooked one thing, you will get a compiler error as you haven't implemented the methods of interfa in the child class
Related
I am learning Java Programming and I am a beginner. I am learning Interfaces now. I came across the below two simple examples and I have doubt in those
Program1
public interface Callback {
void callback(int param);
}
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
void nonIfaceMeth() {
System.out.println("Classes that implement interfaces " +
"may also define other members, too.");
}
}
class TestIface {
public static void main(String args[]) {
Callback c = new Client();
c.callback(42);
// c.nonIfaceMeth();
}
}
Program 2
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
void nonIfaceMeth() {
System.out.println("Classes that implement interfaces " +
"may also define other members, too.");
}
}
class TestIface {
public static void main(String args[]) {
Client c = new Client();
c.callback(42);
}
}
Both Program1 and Program2 give the same output.
In Program1, variable c is declared to be of the interface type and in Program2, variable c is declared to be of the Class type.
My doubt is what is the difference between these two programs and what are the advantages of creating a Interface type variable ?
Kindly help me t understand the concept. TIA
I will try to keep it short as web is full explainaions on interfaces.
Interface is a contract. Many classes can implement an interface. Using interface is one way to loosly couple your code components.
In Program1, variable c is declared to be of the interface type
This means that any implementation of this interface can be taken to create a concrete object and your code should not break.
and in Program2, variable c is declared to be of the Class type.
This means that you have to change your code to use right class every time you need to use a different implementation. Your code is very cohesive.
It will make more sense when you start studing things like dependency injection or factory pattern etc. Also helpful in unit testing.
UPDATE
Based on your comment
I want the difference between these two statements "Callback c = new
Client();" and "Client c = new Client();"
It is very conceptual at the moment but Callback c = new Client() but allows you to change the type of your varible Cat any time. Lets say there is an other implementation ImportantClient in your code where interface is used to declare the variable you can at any time change it to c = new ImportantClient(). However you can not do that if you are using Client c = new Client();
Both are same in your case when saying
Client c = new Client();
Here actually you are just creating an object of a client. And calling a method of the class Client.
And when you say
Callback c = new Client();
You are just creating a reference of type CallBack but at runtime an Object of Client is being created. So both are same in your case.
In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:
interface Bicycle {
// wheel revolutions per minute
void changeCadence(int newValue);
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}
Reference : Oracle JAVA Documentation
Go through : Using an Interface as a Type
One reason to use an interface is when you want to reduce dependencies between classes or components.
If you have a method that can take an interface as a parameter, for example:
public int countItems(List myList) { ... }
... then you are able to pass in any object whose class implements the List interface, without have that dependency hard coded in the method.
In your case, using the interface Callback enables other classes to be used in the code, if they implement the Callback interface.
Another reason is that it buys you flexibility in choice of concrete class. If you create the object and keep a reference to the interface, it restricts you to only interact with the object through the interface's methods. This means that in future, you could change which concrete class you construct, and as long as it implements the interface, your code will continue to work without requiring modification.
I'm trying to reduce some code duplication. Currently i got two methods that are almost identical, the major difference being calling two separate methods within them.
Below is basically what i wanna do:
private void combinedMethod(StandardClass sc, MyClass mc)
{
Method m = null;
if(mc instanceof MySubClass1)
m = sc.RelevantFor1();
if(mc instanceof MySubClass2)
m = sc.RelevantFor2();
m(mc.getA(), mc.getB());
}
I've tested (and it works) this using reflection. But is there a better way of doing it? I read somewhere that reflection is slow and only to be used as a last resort. Is it in this case?
Also in this case the StandardClass is a standard class in the java api. The Class I send in is of my own making.
It isn't clear how exactly those methods look like, or what they are doing, but it seems like a perfect polymorphism case. You can create a method in super class - MyClass I suppose in this case. And override those methods in your subclasses.
Now, when you call that method on MyClass reference, appropriate subclass method will be called based on actual instance. Now invoke whatever method you want to invoke in respective overridden methods.
Somewhere along the lines of:
class MyClass {
public void method(StandardClass sc) { }
}
class MySubClass1 extends MyClass {
public void method(StandardClass sc) {
sc.method(getA(), getB());
}
}
class MySubClass2 extends MyClass {
public void method(StandardClass sc) {
sc.anotherMethod(getA(), getB());
}
}
And then your combinedMethod looks like:
private void combinedMethod(StandardClass sc, MyClass c) {
c.method(sc);
}
I really hope I am just missing something simple, but I am reading the following: http://docs.oracle.com/javase/tutorial/java/IandI/override.html .
I have two classes and one interface. Literally the "use case" shown in this Oracle documentation page. However, when I run a JUnit test - only the method in the superclass gets called and that method has the simple default that I don't want called:
The interface contains this method signature:
public interface RecordServiceInterface {
List<String> searchRecords(String id) throws ServiceException;
}
The superclass which implements the interface contains this method with a default - Eclipse IDE inserts this when it finds a missing method not implemented by the implementing class.
public class RecordService implements RecordServiceInterface {
public List<String> searchRecords(String id) throws ServiceException {
// TODO Auto-generated method stub
return null;
}
}
At runtime, only the above is called as I step through the debugger... every time.
The subclass then extends the superclass and has the real implementation that one wants to override:
public class MyRecordService extends RecordService {
#Override
public List<String> searchRecords(String id) throws ServiceException {
List<String> myList = new ArrayList<String>();
// ...
return myList;
}
}
I must be completely missing the point of #Override. During execution, it repeatedly fails to ever get into the method with the #Override annotation.
All that the #Override annotation does is make the compiler generate an error if there is no corresponding method anywhere in the class inheritance that could be overridden. So it is meant to make sure that your overridden method actually overrides something.
If your method from MyRecordService is not called, but the one from the RecordService class, then I would guess that the wrong object is instanciated. So what you have in front of you is an object of type RecordService, not of type MyRecordService.
Since you have not provided that part of the code, this is just a guess, based on the fact that your inheritance looks fine.
#Override is a compile-time annotation and is used to verify that the annotated method actually overrides something from a superclass / interface. It does not influence runtime behavior.
Post the code for your test so we can get a clearer idea of what you're trying to do.
As you can see in #Override's javadoc, the retention policy of #Override is SOURCE. In other words: it used in compile time but does not make it to the generated binary code (class file).
In particular, the SOURCE retention policy is defined as:
Annotations are to be discarded by the compiler.
#Override is effectively just a way to catch typos when attempting to override a super class' or instance's method, as well as the occasional attempt to override final methods (by design not overridable).
The act of overriding enables a fall-thru approach to overriding method when given a choice of what to call.
For example:
RecordServiceInterface service = new RecordService();
RecordService service2 = new RecordService();
With both service and service2, the implementation from RecordService will be called. Now consider:
RecordServiceInterface service3 = new MyRecordService();
RecordService service4 = new MyRecordService();
MyRecordService service5 = new MyRecordService();
With service3, service4, and service5, the implementation from MyRecordService will be called.
Overriding does not replace methods for parent types unless it is part of the chain (e.g., all three of the instances created in the last block, 3 through 5). If the instance of your Object does is not the type (MyRecordService in this case), then the method is not overridden for that instance with its behavior. service and service2 will still call RecordService's implementation.
It may be more clear with another example:
public interface Runnable {
void run();
}
public class RunnableA implements Runnable {
#Override
public void run() { System.out.println("A"); }
}
public class RunnableB extends RunnableA {
#Override
public void run() { System.out.println("B"); }
}
public class RunnableC implements Runnable {
#Override
public void run() { System.out.println("C"); }
}
You can only have an instance of any one of them, so it will only output one line per call of instance.run(). It depends on the implementation of the instance, and not what exists on the classpath.
I am trying to use a vector to hold my classes. These classes inherit methods from another class and have their own methods as well. What I am having trouble with is using the vector with objects to call the methods from the class within the object. I thought it would be something like:
public static void vSort(Vector<Object> vector) {
vector[0].generate();
}
with generate being a custom method i created with the student class within the object.
A better example
public class Method {
protected String name;
public void method() {
// some code
}
}
public class Student extends Method {
protected String last;
public void setUp() {
// some code
}
}
public class Main {
public static void main(String[] args)
{
Vector<Object> vector = new Vector<Object>();
Student stu = new Student(); // pretend this generates something
vector.add(stu);
}
The problem i am running into is there are many classes like student that build on Method. If i cant use Object that is fine with me but i need to access the code within the Method class.
Java doesn't have operator overloads. So the syntax is:
vector.get(0).generate();
However, this won't work at all in your case, because you have a Vector<Object>, and an Object doesn't have a generate method.
[Tangential note: vector is de facto deprecated; you should probably use ArrayList instead.]
you should use vector.get(0) to retrieve your object.
Also note, that Object does not declare generate() - so you are going to need to cast or specify your object as the generic type.
When you have a Vector<Object>, all the retrieval methods return Object, so you can't call subclass methods unless you explicitly downcast. You should use Vector<YourClass> instead, so that the references you get out of the vector are of type YourClass and you don't have to downcast them.
I know that an interface must be public. However, I don't want that.
I want my implemented methods to only be accessible from their own package, so I want my implemented methods to be protected.
The problem is I can't make the interface or the implemented methods protected.
What is a work around? Is there a design pattern that pertains to this problem?
From the Java guide, an abstract class wouldn't do the job either.
read this.
"The public access specifier indicates that the interface can be used by any class in any package. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface."
Is that what you want?
You class can use package protection and still implement an interface:
class Foo implements Runnable
{
public void run()
{
}
}
If you want some methods to be protected / package and others not, it sounds like your classes have more than one responsibility, and should be split into multiple.
Edit after reading comments to this and other responses:
If your are somehow thinking that the visibility of a method affects the ability to invoke that method, think again. Without going to extremes, you cannot prevent someone from using reflection to identify your class' methods and invoke them. However, this is a non-issue: unless someone is trying to crack your code, they're not going to invoke random methods.
Instead, think of private / protected methods as defining a contract for subclasses, and use interfaces to define the contract with the outside world.
Oh, and to the person who decided my example should use K&R bracing: if it's specified in the Terms of Service, sure. Otherwise, can't you find anything better to do with your time?
When I have butted up against this I use a package accessible inner or nested class to implement the interface, pushing the implemented method out of the public class.
Usually it's because I have a class with a specific public API which must implement something else to get it's job done (quite often because the something else was a callback disguised as an interface <grin>) - this happens a lot with things like Comparable. I don't want the public API polluted with the (forced public) interface implementation.
Hope this helps.
Also, if you truly want the methods accessed only by the package, you don't want the protected scope specifier, you want the default (omitted) scope specifier. Using protected will, of course, allow subclasses to see the methods.
BTW, I think that the reason interface methods are inferred to be public is because it is very much the exception to have an interface which is only implemented by classes in the same package; they are very much most often invoked by something in another package, which means they need to be public.
This question is based on a wrong statement:
I know that an interface must be public
Not really, you can have interfaces with default access modifier.
The problem is I can't make the interface or the implemented methods protected
Here it is:
C:\oreyes\cosas\java\interfaces>type a\*.java
a\Inter.java
package a;
interface Inter {
public void face();
}
a\Face.java
package a;
class Face implements Inter {
public void face() {
System.out.println( "face" );
}
}
C:\oreyes\cosas\java\interfaces>type b\*.java
b\Test.java
package b;
import a.Inter;
import a.Face;
public class Test {
public static void main( String [] args ) {
Inter inter = new Face();
inter.face();
}
}
C:\oreyes\cosas\java\interfaces>javac -d . a\*.java b\Test.java
b\Test.java:2: a.Inter is not public in a; cannot be accessed from outside package
import a.Inter;
^
b\Test.java:3: a.Face is not public in a; cannot be accessed from outside package
import a.Face;
^
b\Test.java:7: cannot find symbol
symbol : class Inter
location: class b.Test
Inter inter = new Face();
^
b\Test.java:7: cannot find symbol
symbol : class Face
location: class b.Test
Inter inter = new Face();
^
4 errors
C:\oreyes\cosas\java\interfaces>
Hence, achieving what you wanted, prevent interface and class usage outside of the package.
Here's how it could be done using abstract classes.
The only inconvenient is that it makes you "subclass".
As per the java guide, you should follow that advice "most" of the times, but I think in this situation it will be ok.
public abstract class Ab {
protected abstract void method();
abstract void otherMethod();
public static void main( String [] args ) {
Ab a = new AbImpl();
a.method();
a.otherMethod();
}
}
class AbImpl extends Ab {
protected void method(){
System.out.println( "method invoked from: " + this.getClass().getName() );
}
void otherMethod(){
System.out.println("This time \"default\" access from: " + this.getClass().getName() );
}
}
Here's another solution, inspired by the C++ Pimpl idiom.
If you want to implement an interface, but don't want that implementation to be public, you can create a composed object of an anonymous inner class that implements the interface.
Here's an example. Let's say you have this interface:
public interface Iface {
public void doSomething();
}
You create an object of the Iface type, and put your implementation in there:
public class IfaceUser {
private int someValue;
// Here's our implementor
private Iface impl = new Iface() {
public void doSomething() {
someValue++;
}
};
}
Whenever you need to invoke doSomething(), you invoke it on your composed impl object.
I just came across this trying to build a protected method with the intention of it only being used in a test case. I wanted to delete test data that I had stuffed into a DB table. In any case I was inspired by #Karl Giesing's post. Unfortunately it did not work. I did figure a way to make it work using a protected inner class.
The interface:
package foo;
interface SomeProtectedFoo {
int doSomeFoo();
}
Then the inner class defined as protected in public class:
package foo;
public class MyFoo implements SomePublicFoo {
// public stuff
protected class ProtectedFoo implements SomeProtectedFoo {
public int doSomeFoo() { ... }
}
protected ProtectedFoo pFoo;
protected ProtectedFoo gimmeFoo() {
return new ProtectedFoo();
}
}
You can then access the protected method only from other classes in the same package, as my test code was as show:
package foo;
public class FooTest {
MyFoo myFoo = new MyFoo();
void doProtectedFoo() {
myFoo.pFoo = myFoo.gimmeFoo();
myFoo.pFoo.doSomeFoo();
}
}
A little late for the original poster, but hey, I just found it. :D
You can go with encapsulation instead of inheritance.
That is, create your class (which won't inherit anything) and in it, have an instance of the object you want to extend.
Then you can expose only what you want.
The obvious disadvantage of this is that you must explicitly pass-through methods for everything you want exposed. And it won't be a subclass...
I would just create an abstract class. There is no harm in it.
With an interface you want to define methods that can be exposed by a variety of implementing classes.
Having an interface with protected methods just wouldn't serve that purpose.
I am guessing your problem can be solved by redesigning your class hierarchy.
One way to get around this is (depending on the situation) to just make an anonymous inner class that implements the interface that has protected or private scope. For example:
public class Foo {
interface Callback {
void hiddenMethod();
}
public Foo(Callback callback) {
}
}
Then in the user of Foo:
public class Bar {
private Foo.Callback callback = new Foo.Callback() {
#Override public void hiddenMethod() { ... }
};
private Foo foo = new Foo(callback);
}
This saves you from having the following:
public class Bar implements Foo.Callback {
private Foo foo = new Foo(this);
// uh-oh! the method is public!
#Override public void hiddenMethod() { ... }
}
I think u can use it now with Java 9 release. From the openJdk notes for Java 9,
Support for private methods in interfaces was briefly in consideration
for inclusion in Java SE 8 as part of the effort to add support for
Lambda Expressions, but was withdrawn to enable better focus on higher
priority tasks for Java SE 8. It is now proposed that support for
private interface methods be undertaken thereby enabling non abstract
methods of an interface to share code between them.
refer https://bugs.openjdk.java.net/browse/JDK-8071453