Can I take as a example to make me/other understand the diff between a interface and class as
java interface is analogus to java specification(JMS APIs)
Java Class is analogous to implementation(ActiveMQ etc) of the specification
An easy way to understand the difference is to think that an interface defines what an object does, while a class defines how it does it.
The analogy that you are suggesting is incomplete, because Java has a concept that is in the middle of an interface and a class, i.e. an abstract class: a specification may be modeled as an abstract class or as an interface.
The difference between a class and an interface is the way they are ran. A class has a main method inside of it. Interfaces are like global files you can place methods into. For example, you have the class Blah
public class Blah {
// NOTICE: this is a method that allows you
// to perform actions within the method
public static void main(String args[]) {
// do whatever
}
}
and you have an interface named BlahInterface
public interface BlahInterface {
public static void main(String args[]);
public void sayBlah();
public int getAmountOfBlahs();
public String getWhatBlahSays();
public int setBlahs(int blahNumber);
}
As you can see, the difference between the class and interface is that the class relies on the interface for the methods that it can implement.
You can see that the class allows the main method to run things within itself, but if you were to try to run the main method within the interface, it wouldn't work.
Summary:
The interface is only to initialize the methods that the class can use/run.
Hope this helps!
Related
Let's say I have 1 complete class with around 20 methods which provide different functionalities.
Now we have multiple clients using this class, but we want them to have restricted access.
For e.g. -
Client 1 - Gets access to method1/m3/m5/m7/m9/m11
Client 2 - Gets access to method2/m4/m6/m8/m10/m12
Is there any way I can restrict this access?
One solution which I thought:
Create 2 new classes extending Parent class and override methods which are not accessible and throw Exception from them.
But then if 3rd client with different requirement, we have to create new subclass for them.
Is there any other way to do this?
Create 2 new classes extending Parent class and override methods which
are not accessible and throw Exception from them. But then if 3rd
client with different requirement, we have to create new subclass for
them.
It is a bad solution because it violates Polymorphism and the Liskov Substitution Principle. This way will make your code less clear.
At first, you should think about your class, are you sure that it isn't overloaded by methods? Are you sure that all of those methods relate to one abstraction? Perhaps, there is a sense to separate methods to different abstractions and classes?
If there is a point in the existence of those methods in the class then you should use different interfaces to different clients. For example, you can make two interfaces for each client
interface InterfaceForClient1 {
public void m1();
public void m3();
public void m5();
public void m7();
public void m9();
public void m11();
}
interface InterfaceForClient2 {
public void m2();
public void m4();
public void m6();
public void m8();
public void m10();
public void m12();
}
And implement them in your class
class MyClass implements InterfaceForClient1, InterfaceForClient2 {
}
After it, clients must use those interfaces instead of the concrete implementation of the class to implement own logic.
You can create an Interface1 which defines methods only for Client1, and an Interface2 which defines methods only for Client2. Then, your class implements Interface1 and Interface2.
When you declare Client1 you can do something like: Interface1 client1.
With this approach, client1 can accesses only methods of this interface.
I hope this will help you.
The other answers already present the idiomatic approach. Another idea is a dynamic proxy decorating the API with an access check.
In essence, you generate a proxy API that has additional checks on method calls to implement a form of Access Control.
Example Implementation:
package com.example;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
#FunctionalInterface
public interface ACL<P, Q> {
boolean allowed(P accessor, Q target, Method method, Object[] args);
class ACLException extends RuntimeException {
ACLException(String message) {
super(message);
}
}
#SuppressWarnings("unchecked")
default Q protect(P accessor, Q delegate, Class<Q> dType) {
if (!dType.isInterface()) {
throw new IllegalArgumentException("Delegate type must be an Interface type");
}
final InvocationHandler handler = (proxy, method, args) -> {
if (allowed(accessor, delegate, method, args)) {
try {
return method.invoke(delegate, args);
} catch (InvocationTargetException e) {
throw e.getCause();
}
} else {
throw new ACLException("Access denies as per ACL");
}
};
return (Q) Proxy.newProxyInstance(dType.getClassLoader(), new Class[]{dType}, handler);
}
}
Example Usage:
package com.example;
import java.lang.reflect.Method;
public class Main {
interface API {
void doAlpha(int arg);
void doBeta(String arg);
void doGamma(Object arg);
}
static class MyAPI implements API {
#Override
public void doAlpha(int arg) {
System.out.println("Alpha");
}
#Override
public void doBeta(String arg) {
System.out.println("Beta");
}
#Override
public void doGamma(Object arg) {
System.out.println("Gamma");
}
}
static class AlphaClient {
void use(API api) {
api.doAlpha(100);
api.doBeta("100");
api.doGamma(this);
}
}
public static class MyACL implements ACL<AlphaClient, API> {
#Override
public boolean allowed(AlphaClient accessor, API target, Method method, Object[] args) {
final String callerName = accessor.getClass().getName().toLowerCase();
final String methodName = method.getName().toLowerCase().replace("do", "");
return callerName.contains(methodName);
}
}
public static void main(String[] args) {
final MyACL acl = new MyACL();
final API api = new MyAPI();
final AlphaClient client = new AlphaClient();
final API guardedAPI = acl.protect(client, api, API.class);
client.use(guardedAPI);
}
}
Notes:
The accessor does not have to be the client object itself, it can be a string key or token that helps ACL identify the client.
The ACL implementation here is rudimentary, more interesting ones could be One that reads ACL from some file or One that uses method and client annotations as rules.
If you don't want to define an interface for API class, consider a tool like javassist to directly proxy a class.
Consider other popular Aspect Oriented Programming solutions
You should create one super class with all the methods and then provide Client specific implementations in their corresponding sub classes extending from the super class defined earlier.
If there are methods which are common implementation for all clients, leave their implementations to the super class.
It seems like you are a bit confused about the purpose of Classes and Interfaces. As far as I know, an Interface is a contract defining which functionality a piece of software provides. This is from official java tutorial:
There are a number of situations in software engineering when it is
important for disparate groups of programmers to agree to a "contract"
that spells out how their software interacts. Each group should be
able to write their code without any knowledge of how the other
group's code is written. Generally speaking, interfaces are such
contracts.
Then you can write a Class which implements this Interface/contract, that is, provides the code that actually perform what was specified. The List interface and the ArrayList class are both an example of this.
Interfaces and Classes have access modifiers, but they aren't designed to specify permissions to specific clients. They specify what is visible for other piece of software depending the location where it is defined: Class, Package, Subclass, World. For example, a private method can be accessed only inside the class where it is defined.
From official Java tutorial again:
Access level modifiers determine whether other classes can use a
particular field or invoke a particular method. There are two levels
of access control:
At the top level—public, or package-private (no explicit modifier).
At the member level—public, private, protected, or package-private (no
explicit modifier).
Maybe you want something more powerful like Access Control List (ACL).
Your question is a little unclear, leading to different possible answers. I'll try to cover some of the possible areas:
Object encapsulation
If your goal is to provide interfaces to different clients that only provide certain functionality or a specific view there are several solutions. Which matches best depends on the purpose of your class:
Refactoring
The question somehow suggests that your class is responsible for different tasks. That might be an indicator, that you could tear it apart into distinct classes that provide the different interfaces.
Original
class AllInOne {
A m1() {}
B m2() {}
C m3() {}
}
client1.useClass(allInOneInstance);
client2.useClass(allInOneInstance);
client3.useClass(allInOneInstance);
Derived
class One {
A m1() {}
}
class Two {
B m2() {}
}
class Three {
C m3() {}
}
client1.useClass(oneInstance);
client2.useClass(twoInstance);
client3.useClass(threeInstance);
Interfaces
If you choose to keep the class together (there might be good reasons for it), you could have the class implement interfaces that model the view required by different clients. By passing instances of the appropriate interface to the clients they will not see the full class interface:
Example
class AllInOne implements I1, I2, I3 {
...
}
interface I1 {
A m1();
}
But be aware that clients will still be able to cast to the full class like ((AllInOne) i1Instance).m2().
Inheritance
This was already outline in other answers. I'll therefore skip this here. I don't think this is a good solution as it might easily break in a lot of scenarios.
Delegation
If casting is a risk to you, you can create classes that only offer the desired interface and delegate to the actual implementation:
Example
class Delegate1 {
private AllInOne allInOne;
public A m1() {
return allInOne.m1();
}
}
Implementing this can be done in various ways and depends on your environment like explicit classes, dynamic proxies , code generation, ...
Framework
If you are using an Application Framework like Spring you might be able to use functionality from this Framework.
Aspects
AOP allows you to intercept method calls and therefor apply some access control logic there.
Security
Please note that all of the above solutions will not give you actual security. Using casts, reflection or other techniques will still allow clients to obtain access to the full functionality.
If you require stronger access limitations there are techniques that I will just briefly outline as they might depend on your environment and are more complex.
Class Loader
Using different class loaders you can make sure that parts of your code have no access to class definitions outsider their scope (used e.g. in tomcat to isolate different deployments).
SecurityManager
Java offers possibilities to implement your own SecurityManager this offers ways to add some extra level of access checking.
Custom build Security
Of course you can add your own access checking logic. Yet I don't think this will be a viable solution for in JVM method access.
I hear that in Java I can achieve polymorphism through injection at runtime. Can someone please show a simple example of how that is done? I search online but I can't find anything: maybe I am searching wrong. So I know about polymorphism through interface and and extension such as
class MyClass extends Parent implements Naming
in such case I am achieving polymorphism twice: MyClass is at once of type Parent and Naming. But I don't get how injection works. The idea is that I would not be using the #Override keyword during injection. I hope the question is clear. Thanks.
So the end result here, per my understanding, is to change the behavior of a method through injection instead of by #Override it during development.
So I know about polymorphism through interface and and extension such as
class MyClass extends Parent implements Naming
This is known as inhertiance and not polymorphism. MyClassis a Parent and MyClass is also a Naming. That being said, inheritance allows you to achive polymorphism.
Consider a class other thanMyClass that also implements Naming :
class SomeOtherClass implements Naming {
#Override
public void someMethodDefinedInTheInterface() {
}
}
Now consider a method that takes a Naming argument somewhere in your code base :
public void doSomething(Naming naming) {
naming.someMethodDefinedInTheInterface();
}
The doSomething method can be passed an instance of any class that implements Naming. So both the following calls are valid :
doSomething(new MyClass());//1
doSomething(new SomeOtherClass());//2
Observe how you can call doSomething with different parameters. At runtime, the first call will call someMethodDefinedInTheInterface from MyClass and the second call will call someMethodDefinedInTheInterface from SomeOtherClass. This is known as runtime-polymorphism which can be achieved through inheritance.
But I don't get how injection works. The idea is that I would not be using the #Override keyword during injection
That's true in the broader sense. To inject something into a class, the class should ideally favor composition over inheritance. See this answer that does a good job in explaining the reason for favoring composition over inheritance.
To extend the above example from my answer, let's modify the doSomething method as follows :
public class ClassHasANaming {
private Naming naming;
public ClassHasANaming(Naming naming) {
this.naming = naming;
}
public void doSomething() {
naming.someMethodDefinedInTheInterface();
}
}
Observe how ClassHasANaming now has-a Naming dependency that can be injected from the outside world :
ClassHasANaming callMyClass = new ClassHasANaming(new MyClass());
callMyClass.doSomething();
If you use the Factory pattern, you can actually chose which subclass gets instantiated at runtime.
Do you think we could have done what we did above using inheritance?
public class ClassIsANaming implements Naming {
public void doSomething() {
someMethodDefinedInTheInterface();
}
#Override
public void someMethodDefinedInTheInterface() {
//....
}
}
The answer is No. ClassIsANaming is bound to a single implementation of the someMethodDefinedInTheInterface method at compile time itself.
`
Taking a contrived example. You have a class Store that stores things:
class Store {
private List l
void store(Object o) {
l.add(o);
}
void setStoreProvider(List l) {
this.l = l
}
}
You can inject the actual List used as the backing storage using setStoreProvider which could be a linked list, array backed list, whatever.
Hence, depending on the injected type your Store class would have the features of the injected type (with regards to memory usage, speed, etc).
This is a kind of polymorphism without the class implementing an interface.
EDIT 1: By generic I don't mean a generic method for java's generic classes, but a method that I have written to be essential in the use of my program.
I'm trying to write a program (sort of a process integrator) that allows 3rd party developers to add their own functional pieces to a task net. These pieces are objects created from classes which have a runProcess()-method (the class implements specialRunnable).
I wan't to force a log entry to be written whenever the object's runProcess()- method is called. However, I don't want the implementation (writing to log) to be neither in the 3rd party class nor in the class which makes the method call.
I've searched and tried to do it trough inheritance and implementing an interface, but haven't found a solution. Here's and example of how I would like it to work:
public abstract class Process{
public void runProcess(){
// when runProcess() is called all specialized processes write to log first
writeToLog();
// then do their thing which is defined in their class
doYourProcessSpecificThing();
}
public void writeToLog(){
//writing to log comes here
}
// specialized processes have to define what is done
public abstract void doYourProcessSpecificThing();
Specialized class:
public class Special3rdPartyProcess extends Process implements specialRunnable{
runProcess(){
super.runProcess();
}
doYourProcessSpecificThing(){
// this is where the magic happens
}
To sum what I want: I want all processes to be started with runProcess() command, and I want a log entry whenever it is done, but I DON'T want the 3rd party developers to decide how or if the entry is written. Also I don't want it done like this:
writeToLog();
task1.runProcess();
writeToLog();
task2.runProcess
Thanks!
If you make your runProcess method final, then subclasses won't be able to override your method, and this can ensure that writeToLog is called.
You can make writeToLog private to not expose the implementation.
You can make doYourProcessSpecificThing protected so that it can't be called directly, but subclasses can still define their own implementation.
This is called the Template Method Pattern. This allows the implementer (you) to define what specific behavior can be overridden, yet retaining control over the overall process/algorithm.
You can simply make runProcess final in the base class, so subclasses can't override it:
public abstract class Process{
public final void runProcess(){
writeToLog();
doYourProcessSpecificThing();
}
//private: implementation detail
private void writeToLog(){
}
//protected: calling classes don't need to know about this method
protected abstract void doYourProcessSpecificThing();
And your subclass:
public class Special3rdPartyProcess extends Process implements specialRunnable{
protected final void doYourProcessSpecificThing(){
// this is where the magic happens
}
}
Then the client code simply does:
Special3rdPartyProcess spp = ...;
spp.runProcess();
Are private interfaces ever used in design decisions ? If so, what are the reasons and when do you know the need for a private interface?
A top-level interface cannot be private. It can only have public or package access. From the Java Language Specification, section 9.1.1: "Interface Modifiers":
The access modifiers protected and private pertain only to member interfaces whose declarations are directly enclosed by a class declaration (§8.5.1).
A nested interface can be private whenever it and its subclasses, if any, are an implementation detail of its top-level class.
For example, the nested interface CLibrary below is used as an implementation detail of the top-level class. It's used purely to define an API for JNA, communicated by the interface's Class.
public class ProcessController {
private interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary) Native.loadLibrary( "c", CLibrary.class );
int getpid();
}
public static int getPid() {
return CLibrary.INSTANCE.getpid();
}
}
As another example, this private interface defines an API used by private nested classes implementing custom formatting symbols.
public class FooFormatter {
private interface IFormatPart {
/** Formats a part of Foo, or text.
* #param foo Non-null foo object, which may be used as input.
*/
void write( Foo foo ) throws IOException;
}
private class FormatSymbol implements IFormatPart { ... }
private class FormatText implements IFormatPart { ... }
...
}
IMHO You cannot usefully make an interface private.
However I often have two interfaces, one for public use and one for internal use. The internal use interface I make package local if possible e.g.
public interface MyInterface {
public void publicMethod();
}
interface DirectMyInterface extends MyInterface {
public void internalUseOnlyMethod();
}
The internal use methods expose methods I don't want other developers to use and/or I want to be able to change easily. The reason I have the interface at all is that I have several implementations which I want to use internally via an interface.
It has to be package protected if the interface if for internal use.
In general if the interface hasn't any interest outside it's ambit it's a good api design decision to hide it because there's less complexity for the users of the interface and also allows you to refactor it more easily, because when the interface is public and in the API you loss the liberty to change it.
A private interface method is a method that is only accessible within the class or object in which it is defined.
This allows for better organization and maintainability of code, as well as increased security by preventing external access to sensitive data or functionality.
I have just started learning Scala and I'm now wondering how I could implement two different Java interfaces with one Scala class? Let's say I have the following interfaces written in Java
public interface EventRecorder {
public void abstract record(Event event);
}
public interface TransactionCapable {
public void abstract commit();
}
But a Scala class can extend only one class at a time. How can I have a Scala class that could fulfill both contracts? Do I have to map those interfaces into traits?
Note, my Scala classes would be used from Java as I am trying to inject new functionality written in Scala into an existing Java application. And the existing framework expects that both interface contracts are fulfilled.
The second interface can be implemented with the with keyword
class ImplementingClass extends EventRecorder with TransactionCapable {
def record(event: Event) {}
def commit() {}
}
Further on each subsequent interface is separated with the keyword with.
class Clazz extends InterfaceA
with InterfaceB
with InterfaceC {
//...
}