How do I combine two objects in Java? - java

Consider:
public class test01{
public void doSomething(){
// do something
}
}
public class test02{
public void printSomething(){
// print something
}
}
// in main
test01 t1 = new test01();
test02 t2 = new test02();
// I want do to something like this
test01 t3 = t1.merge(t2);
// with t3 I should be able to access both t1 and t2 functions
t3.doSomething();
t3.printSomething();
Please let me know if this is possible in Java? If yes, then let me know how can I achieve this?

There is no multiple inheritance in java. What you can do is making test02 a subclass of test01 then create test03 as a subclass of test02.
OR
you can compose them into a Test03 class like this:
public class Test03 {
private Test01 test01;
private Test02 test02;
public void doSomething() {
test01.doSomething();
}
public void printSomething() {
test02.printSomething();
}
}
Please note that in java you shouldn't use class names like test01. They should be meaningful and comform to the java class naming guidelines.

Your best option is probably this:
public class TestSet {
private test01 t1 = new test01();
private test02 t2 = new test02();
public void doSomething() {
t1.doSomething();
}
public void printSomething() {
t2.printSomething();
}
}
In some languages, multiple inheritance is supported, which may be what you're looking for here. But not in Java. You may or may not want to make a couple of interfaces here to tie TestSet more closely together with test01 and test02.

Please let me know if this is possible in Java?
It is not possible. You cannot combine behaviour dynamically like that in Java.
The normal way to combine behaviour in Java is to use some combination of inheritance and wrappering or delegation. Even then, there will be an issue of subtyping ... unless you use interfaces ... because Java does not allow a class to have multiple (direct) superclasses.
Consider for #Panzercrisis's example. While his test03 class implements methods with the same signatures as the test01 and test02 classes, an instance of test03 is not type compatible with either of them. (You can't use a test03 instance as a test01 or a test02. Java doesn't support duck typing!)
To address that you would need to define interfaces face01 and face02 that are implemented by test01 and test02 respectively. Then you would implement test03 as implementing both face01 and face02.
But this is all static classes and static typing.
Under some circumstances, you could use DynamicProxy or something similar to "synthesize" a class that "merges" the behaviour of two existing classes. However, that is all done with static types and code generation behind the scenes. Moreover, this approach would only viable if you'd had the foresight to define a bunch of interfaces (e.g. face01 and face02) and write your application code against the interfaces rather than the implementation classes.

You can define a class Y in another class X as inner class and you can use class Y in class X. Other than that, as I know there is no way to do that.

Short answer, no it's not possible how you describe.
The appearance of doing this might be possible if test01 and test02 where interfaces and you had a third class test03 implement both. In C++ this would be done by multiple inheritance but that would function much the same way (i.e. you would have to create a third class that instead extends both) and this option isn't available in Java anyway.
Another option would be some sort of composition such as #Panzercrisis describes.
The final option (I can think of) would be to have test02 extend test01 but that alters test02.
But generally, no, not possible.

No you can't, really do this in way how you describe this,
you can do
public class test01 extend test02{ ....
}
so your test1, you can use methods from both classes,
but if you can really whant yo play with merging classes together, you can do some abomination like this one:
public class MyObject {
Map<String, Object> objects = new HashMap<String, Object>();
Map<String, Method> methods = new HashMap<String, Method>();
public Object execute(String methodAName)
{
Object object = objects.get(methodAName);
Method method = methods.get(methodAName);
if (object==null || method==null)
{
throw new RuntimeException("method not found");
}
try {
return method.invoke(object, null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void merge(Object o) {
for (Method m : o.getClass().getMethods()) {
objects.put(m.getName(), o);
methods.put(m.getName(), m);
}
}
}
and when you can use it like that
MyObject o = new MyObject();
o.merge(new test01());
o.merge(new test02());
o.execute("printSomething");
o.execute("doSomething");
but as i said, not recommended

You can do something similar using Java inheritance, But not the same thing. you can use extends here. But you have to make sure method overriding not happen else your requirement not match.
Test02 extends Test01
Then
Test03 extends Test02
Now you can achieve some thing similar.
Test03 test=new Test03();
test.callMethodInTest1();
test.callMethodInTest2();
Sample:
public class Test1 {
public String callMethodInTest1() {
return "test1";
}
}
.
public class Test2 extends Test1{
public String callMethodInTest2() {
return "test2";
}
}
.
public class Test03 extends Test2 {
public static void main(String[] args){
Test03 sample=new Test03();
sample.callMethodInTest1();
sample.callMethodInTest2();
}
}

Related

What pattern should be used, strategy?

I do have a service which needs to handle two types of meal.
#Service
class MealService {
private final List<MealStrategy> strategies;
MealService(…) {
this.strategies = strategies;
}
void handle() {
var foo = …;
var bar = …;
strategies.forEach(s -> s.remove(foo, bar));
}
}
There are two strategies, ‘BurgerStrategy’ and ‘PastaStrategy’. Both implements Strategy interface with one method called remove which takes two parameters.
BurgerStrategy class retrieves meals of enum type burger from the database and iterate over them and perform some operations. Similar stuff does the PastaStrategy.
The question is, does it make sense to call it Strategy and implement it this way or not?
Also, how to handle duplications of the code in those two services, let’s say both share the same private methods. Does it make sense to create a Helper class or something?
does it make sense to call it Strategy and implement it this way or not
I think these classes ‘BurgerStrategy’ and ‘PastaStrategy’ have common behaviour. Strategy pattern is used when you want to inject one strategy and use it. However, you are iterating through all behaviors. You did not set behaviour by getting one strategy and stick with it. So, in my honour opinion, I think it is better to avoid Strategy word here.
So strategy pattern would look like this. I am sorry, I am not Java guy. Let me show via C#. But I've provided comments of how code could look in Java.
This is our abstraction of strategy:
public interface ISoundBehaviour
{
void Make();
}
and its concrete implementation:
public class DogSound : ISoundBehaviour // implements in Java
{
public void Make()
{
Console.WriteLine("Woof");
}
}
public class CatSound : ISoundBehaviour
{
public void Make()
{
Console.WriteLine("Meow");
}
}
And then we stick with one behaviour that can also be replaced:
public class Dog
{
ISoundBehaviour _soundBehaviour;
public Dog(ISoundBehaviour soundBehaviour)
{
_soundBehaviour = soundBehaviour;
}
public void Bark()
{
_soundBehaviour.Make();
}
public void SetAnotherSound(ISoundBehaviour anotherSoundBehaviour)
{
_soundBehaviour = anotherSoundBehaviour;
}
}
how to handle duplications of the code in those two services, let’s say both share the same private methods.
You can create one base, abstract class. So basic idea is to put common logic into some base common class. Then we should create abstract method in abstract class. Why? By doing this, subclasses will have particular logic for concrete case. Let me show an example.
An abstract class which has common behaviour:
public abstract class BaseMeal
{
// I am not Java guy, but if I am not mistaken, in Java,
// if you do not want method to be overriden, you shoud use `final` keyword
public void CommonBehaviourHere()
{
// put here code that can be shared among subclasses to avoid code duplication
}
public abstract void UnCommonBehaviourShouldBeImplementedBySubclass();
}
And its concrete implementations:
public class BurgerSubclass : BaseMeal // extends in Java
{
public override void UnCommonBehaviourShouldBeImplementedBySubclass()
{
throw new NotImplementedException();
}
}
public class PastaSubclass : BaseMeal // extends in Java
{
public override void UnCommonBehaviourShouldBeImplementedBySubclass()
{
throw new NotImplementedException();
}
}

Using Java generics instead of reflection to access common functionality of subclassed objects

I am trying to figure out if generics would be a better way to do what I'm trying to accomplish below (or some other way) instead of using reflection (which I currently have working just fine, but don't like it...).
I have a class library I'm using that is roughly like the following:
abstract class base<T>{
public boolean method1 (String who) {
System.out.println(who+":s");
return true;
}
public T method2 (String who) {
System.out.println(who+":d");
// The following gives me an unchecked cast warning. I can't figure out
// the proper way to fix that either, but it works, so I've moved on...
// In the main program, it's this: obj = (T) in.readObject();
// basically deserializing the object from disk.
return (T) new Object();
}
public abstract void load();
}
class Api1 extends base{
#Override
public void load(){
System.out.println("api1:load()");
}
}
class Api2 extends base{
#Override
public void load(){
System.out.println("api2:load()");
}
}
I am trying to wrap the above class library using the code below... This is what I cannot figure out how to do. The objects that are passed to init() have the same methods (method1(), method2() and load()). I don't want to write init() for each class type, instead, I just want to write it once, then have the compiler handle the details.
UPDATE: There are currently 6 classes that are derived from Base (with a few more likely). In the wrapper, I'm just trying to simplify access to the underlying APIs by handling various housekeeping chores automatically. In the init() method, I need to be able to call the methods of those underlying objects (based on Api1, Api2, ...), without using reflection, or without writing duplicate code for each class, or getting a bunch of unchecked warnings and/or casting...
class ApiWrapper<T>{
// would like to return the type passed in if that's doable
// e.g. public T init(T t)
public void init(T t){
System.out.println("inside init: "+t.getClass().toString());
//t.method1(t.getClass().toString());
//t.method2(t.getClass().toString());
//t.load();
}
}
class api1Wrap extends ApiWrapper {
Api1 api = new Api1();
public api1Wrap(){
init(api);
}
}
class api2Wrap extends ApiWrapper {
Api2 api = new Api2();
public api2Wrap(){
init(api);
}
}
public class GenericApiWrapper {
private final api1Wrap api1;
private final api2Wrap api2;
public GenericApiWrapper() {
this.api1 = new api1Wrap();
this.api2 = new api2Wrap();
}
}
From a main() somewhere ...
GenericApiWrapper gaw = new GenericApiWrapper();
It feels to me like generics are the right approach for this type of thing, but I've been trying all sorts of combinations, and reviewing various articles and examples, but I just can't seem to figure out the proper approach. If this has already been asked and answered, please point me to it. I can't seem to find it, probably because I'm not sure how to describe what I'm trying to do. :) I've been looking at the Java Generics FAQ as well, but I haven't found what I'm looking for... Thanks in advance!
In generics you should specify the type you want to use, in this case you replace the T with for example Api1 otherwise the compiler uses Object:
class api1Wrap extends ApiWrapper<Api1> {
Api1 api = new Api1();
public api1Wrap(){
init(api);
}
}
Also you could improve your code by simple implementing one single class and creating several instances with different types, this is the idea behind generics.
UPDATE:
If you also specify that T extends base, then the compiler is able to find the methods.
Take a look at this:
class ApiWrapper<K, T extends base<K>>{
private T t;
public ApiWrapper(T t){
this.t = t;
}
public void wrap(){
init(t)
}
private void init(T t){
t.method1("hello");
K k = t.method2("world");
}
}
ApiWrapper<Object, Api1> apiWrapper1 = new ApiWrapper<>(new Api1());

Why is this variable's type its own class? [duplicate]

What is the use of anonymous classes in Java? Can we say that usage of anonymous class is one of the advantages of Java?
By an "anonymous class", I take it you mean anonymous inner class.
An anonymous inner class can come useful when making an instance of an object with certain "extras" such as overriding methods, without having to actually subclass a class.
I tend to use it as a shortcut for attaching an event listener:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// do something
}
});
Using this method makes coding a little bit quicker, as I don't need to make an extra class that implements ActionListener -- I can just instantiate an anonymous inner class without actually making a separate class.
I only use this technique for "quick and dirty" tasks where making an entire class feels unnecessary. Having multiple anonymous inner classes that do exactly the same thing should be refactored to an actual class, be it an inner class or a separate class.
Anonymous inner classes are effectively closures, so they can be used to emulate lambda expressions or "delegates". For example, take this interface:
public interface F<A, B> {
B f(A a);
}
You can use this anonymously to create a first-class function in Java. Let's say you have the following method that returns the first number larger than i in the given list, or i if no number is larger:
public static int larger(final List<Integer> ns, final int i) {
for (Integer n : ns)
if (n > i)
return n;
return i;
}
And then you have another method that returns the first number smaller than i in the given list, or i if no number is smaller:
public static int smaller(final List<Integer> ns, final int i) {
for (Integer n : ns)
if (n < i)
return n;
return i;
}
These methods are almost identical. Using the first-class function type F, we can rewrite these into one method as follows:
public static <T> T firstMatch(final List<T> ts, final F<T, Boolean> f, T z) {
for (T t : ts)
if (f.f(t))
return t;
return z;
}
You can use an anonymous class to use the firstMatch method:
F<Integer, Boolean> greaterThanTen = new F<Integer, Boolean> {
Boolean f(final Integer n) {
return n > 10;
}
};
int moreThanMyFingersCanCount = firstMatch(xs, greaterThanTen, x);
This is a really contrived example, but its easy to see that being able to pass functions around as if they were values is a pretty useful feature. See "Can Your Programming Language Do This" by Joel himself.
A nice library for programming Java in this style: Functional Java.
Anonymous inner class is used in following scenario:
1.) For Overriding(subclassing), when class definition is not usable except current case:
class A{
public void methodA() {
System.out.println("methodA");
}
}
class B{
A a = new A() {
public void methodA() {
System.out.println("anonymous methodA");
}
};
}
2.) For implementing an interface, when implementation of interface is required only for current case:
interface InterfaceA{
public void methodA();
}
class B{
InterfaceA a = new InterfaceA() {
public void methodA() {
System.out.println("anonymous methodA implementer");
}
};
}
3.) Argument Defined Anonymous inner class:
interface Foo {
void methodFoo();
}
class B{
void do(Foo f) { }
}
class A{
void methodA() {
B b = new B();
b.do(new Foo() {
public void methodFoo() {
System.out.println("methodFoo");
}
});
}
}
I use them sometimes as a syntax hack for Map instantiation:
Map map = new HashMap() {{
put("key", "value");
}};
vs
Map map = new HashMap();
map.put("key", "value");
It saves some redundancy when doing a lot of put statements. However, I have also run into problems doing this when the outer class needs to be serialized via remoting.
They're commonly used as a verbose form of callback.
I suppose you could say they're an advantage compared to not having them, and having to create a named class every time, but similar concepts are implemented much better in other languages (as closures or blocks)
Here's a swing example
myButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// do stuff here...
}
});
Although it's still messily verbose, it's a lot better than forcing you to define a named class for every throw away listener like this (although depending on the situation and reuse, that may still be the better approach)
You use it in situations where you need to create a class for a specific purpose inside another function, e.g., as a listener, as a runnable (to spawn a thread), etc.
The idea is that you call them from inside the code of a function so you never refer to them elsewhere, so you don't need to name them. The compiler just enumerates them.
They are essentially syntactic sugar, and should generally be moved elsewhere as they grow bigger.
I'm not sure if it is one of the advantages of Java, though if you do use them (and we all frequently use them, unfortunately), then you could argue that they are one.
GuideLines for Anonymous Class.
Anonymous class is declared and initialized simultaneously.
Anonymous class must extend or implement to one and only one class or interface resp.
As anonymouse class has no name, it can be used only once.
eg:
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
});
Yes, anonymous inner classes is definitely one of the advantages of Java.
With an anonymous inner class you have access to final and member variables of the surrounding class, and that comes in handy in listeners etc.
But a major advantage is that the inner class code, which is (at least should be) tightly coupled to the surrounding class/method/block, has a specific context (the surrounding class, method, and block).
new Thread() {
public void run() {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
System.out.println("Exception message: " + e.getMessage());
System.out.println("Exception cause: " + e.getCause());
}
}
}.start();
This is also one of the example for anonymous inner type using thread
An inner class is associated with an instance of the outer class and there are two special kinds: Local class and Anonymous class. An anonymous class enables us to declare and instantiate a class at same time, hence makes the code concise. We use them when we need a local class only once as they don't have a name.
Consider the example from doc where we have a Person class:
public class Person {
public enum Sex {
MALE, FEMALE
}
String name;
LocalDate birthday;
Sex gender;
String emailAddress;
public int getAge() {
// ...
}
public void printPerson() {
// ...
}
}
and we have a method to print members that match search criteria as:
public static void printPersons(
List<Person> roster, CheckPerson tester) {
for (Person p : roster) {
if (tester.test(p)) {
p.printPerson();
}
}
}
where CheckPerson is an interface like:
interface CheckPerson {
boolean test(Person p);
}
Now we can make use of anonymous class which implements this interface to specify search criteria as:
printPersons(
roster,
new CheckPerson() {
public boolean test(Person p) {
return p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25;
}
}
);
Here the interface is very simple and the syntax of anonymous class seems unwieldy and unclear.
Java 8 has introduced a term Functional Interface which is an interface with only one abstract method, hence we can say CheckPerson is a functional interface. We can make use of Lambda Expression which allows us to pass the function as method argument as:
printPersons(
roster,
(Person p) -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25
);
We can use a standard functional interface Predicate in place of the interface CheckPerson, which will further reduce the amount of code required.
i use anonymous objects for calling new Threads..
new Thread(new Runnable() {
public void run() {
// you code
}
}).start();
Anonymous inner class can be beneficial while giving different implementations for different objects. But should be used very sparingly as it creates problem for program readability.
One of the major usage of anonymous classes in class-finalization which called finalizer guardian. In Java world using the finalize methods should be avoided until you really need them. You have to remember, when you override the finalize method for sub-classes, you should always invoke super.finalize() as well, because the finalize method of super class won't invoke automatically and you can have trouble with memory leaks.
so considering the fact mentioned above, you can just use the anonymous classes like:
public class HeavyClass{
private final Object finalizerGuardian = new Object() {
#Override
protected void finalize() throws Throwable{
//Finalize outer HeavyClass object
}
};
}
Using this technique you relieved yourself and your other developers to call super.finalize() on each sub-class of the HeavyClass which needs finalize method.
You can use anonymous class this way
TreeSet treeSetObj = new TreeSet(new Comparator()
{
public int compare(String i1,String i2)
{
return i2.compareTo(i1);
}
});
Seems nobody mentioned here but you can also use anonymous class to hold generic type argument (which normally lost due to type erasure):
public abstract class TypeHolder<T> {
private final Type type;
public TypeReference() {
// you may do do additional sanity checks here
final Type superClass = getClass().getGenericSuperclass();
this.type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
}
public final Type getType() {
return this.type;
}
}
If you'll instantiate this class in anonymous way
TypeHolder<List<String>, Map<Ineger, Long>> holder =
new TypeHolder<List<String>, Map<Ineger, Long>>() {};
then such holder instance will contain non-erasured definition of passed type.
Usage
This is very handy for building validators/deserializators. Also you can instantiate generic type with reflection (so if you ever wanted to do new T() in parametrized type - you are welcome!).
Drawbacks/Limitations
You should pass generic parameter explicitly. Failing to do so will lead to type parameter loss
Each instantiation will cost you additional class to be generated by compiler which leads to classpath pollution/jar bloating
An Anonymous Inner Class is used to create an object that will never be referenced again. It has no name and is declared and created in the same statement.
This is used where you would normally use an object's variable. You replace the variable with the new keyword, a call to a constructor and the class definition inside { and }.
When writing a Threaded Program in Java, it would usually look like this
ThreadClass task = new ThreadClass();
Thread runner = new Thread(task);
runner.start();
The ThreadClass used here would be user defined. This class will implement the Runnable interface which is required for creating threads. In the ThreadClass the run() method (only method in Runnable) needs to be implemented as well.
It is clear that getting rid of ThreadClass would be more efficient and that's exactly why Anonymous Inner Classes exist.
Look at the following code
Thread runner = new Thread(new Runnable() {
public void run() {
//Thread does it's work here
}
});
runner.start();
This code replaces the reference made to task in the top most example. Rather than having a separate class, the Anonymous Inner Class inside the Thread() constructor returns an unnamed object that implements the Runnable interface and overrides the run() method. The method run() would include statements inside that do the work required by the thread.
Answering the question on whether Anonymous Inner Classes is one of the advantages of Java, I would have to say that I'm not quite sure as I am not familiar with many programming languages at the moment. But what I can say is it is definitely a quicker and easier method of coding.
References: Sams Teach Yourself Java in 21 Days Seventh Edition
The best way to optimize code. also, We can use for an overriding method of a class or interface.
import java.util.Scanner;
abstract class AnonymousInner {
abstract void sum();
}
class AnonymousInnerMain {
public static void main(String []k){
Scanner sn = new Scanner(System.in);
System.out.println("Enter two vlaues");
int a= Integer.parseInt(sn.nextLine());
int b= Integer.parseInt(sn.nextLine());
AnonymousInner ac = new AnonymousInner(){
void sum(){
int c= a+b;
System.out.println("Sum of two number is: "+c);
}
};
ac.sum();
}
}
One more advantage:
As you know that Java doesn't support multiple inheritance, so if you use "Thread" kinda class as anonymous class then the class still has one space left for any other class to extend.

What does the following code snippet do? [duplicate]

What is the use of anonymous classes in Java? Can we say that usage of anonymous class is one of the advantages of Java?
By an "anonymous class", I take it you mean anonymous inner class.
An anonymous inner class can come useful when making an instance of an object with certain "extras" such as overriding methods, without having to actually subclass a class.
I tend to use it as a shortcut for attaching an event listener:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// do something
}
});
Using this method makes coding a little bit quicker, as I don't need to make an extra class that implements ActionListener -- I can just instantiate an anonymous inner class without actually making a separate class.
I only use this technique for "quick and dirty" tasks where making an entire class feels unnecessary. Having multiple anonymous inner classes that do exactly the same thing should be refactored to an actual class, be it an inner class or a separate class.
Anonymous inner classes are effectively closures, so they can be used to emulate lambda expressions or "delegates". For example, take this interface:
public interface F<A, B> {
B f(A a);
}
You can use this anonymously to create a first-class function in Java. Let's say you have the following method that returns the first number larger than i in the given list, or i if no number is larger:
public static int larger(final List<Integer> ns, final int i) {
for (Integer n : ns)
if (n > i)
return n;
return i;
}
And then you have another method that returns the first number smaller than i in the given list, or i if no number is smaller:
public static int smaller(final List<Integer> ns, final int i) {
for (Integer n : ns)
if (n < i)
return n;
return i;
}
These methods are almost identical. Using the first-class function type F, we can rewrite these into one method as follows:
public static <T> T firstMatch(final List<T> ts, final F<T, Boolean> f, T z) {
for (T t : ts)
if (f.f(t))
return t;
return z;
}
You can use an anonymous class to use the firstMatch method:
F<Integer, Boolean> greaterThanTen = new F<Integer, Boolean> {
Boolean f(final Integer n) {
return n > 10;
}
};
int moreThanMyFingersCanCount = firstMatch(xs, greaterThanTen, x);
This is a really contrived example, but its easy to see that being able to pass functions around as if they were values is a pretty useful feature. See "Can Your Programming Language Do This" by Joel himself.
A nice library for programming Java in this style: Functional Java.
Anonymous inner class is used in following scenario:
1.) For Overriding(subclassing), when class definition is not usable except current case:
class A{
public void methodA() {
System.out.println("methodA");
}
}
class B{
A a = new A() {
public void methodA() {
System.out.println("anonymous methodA");
}
};
}
2.) For implementing an interface, when implementation of interface is required only for current case:
interface InterfaceA{
public void methodA();
}
class B{
InterfaceA a = new InterfaceA() {
public void methodA() {
System.out.println("anonymous methodA implementer");
}
};
}
3.) Argument Defined Anonymous inner class:
interface Foo {
void methodFoo();
}
class B{
void do(Foo f) { }
}
class A{
void methodA() {
B b = new B();
b.do(new Foo() {
public void methodFoo() {
System.out.println("methodFoo");
}
});
}
}
I use them sometimes as a syntax hack for Map instantiation:
Map map = new HashMap() {{
put("key", "value");
}};
vs
Map map = new HashMap();
map.put("key", "value");
It saves some redundancy when doing a lot of put statements. However, I have also run into problems doing this when the outer class needs to be serialized via remoting.
They're commonly used as a verbose form of callback.
I suppose you could say they're an advantage compared to not having them, and having to create a named class every time, but similar concepts are implemented much better in other languages (as closures or blocks)
Here's a swing example
myButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// do stuff here...
}
});
Although it's still messily verbose, it's a lot better than forcing you to define a named class for every throw away listener like this (although depending on the situation and reuse, that may still be the better approach)
You use it in situations where you need to create a class for a specific purpose inside another function, e.g., as a listener, as a runnable (to spawn a thread), etc.
The idea is that you call them from inside the code of a function so you never refer to them elsewhere, so you don't need to name them. The compiler just enumerates them.
They are essentially syntactic sugar, and should generally be moved elsewhere as they grow bigger.
I'm not sure if it is one of the advantages of Java, though if you do use them (and we all frequently use them, unfortunately), then you could argue that they are one.
GuideLines for Anonymous Class.
Anonymous class is declared and initialized simultaneously.
Anonymous class must extend or implement to one and only one class or interface resp.
As anonymouse class has no name, it can be used only once.
eg:
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
});
Yes, anonymous inner classes is definitely one of the advantages of Java.
With an anonymous inner class you have access to final and member variables of the surrounding class, and that comes in handy in listeners etc.
But a major advantage is that the inner class code, which is (at least should be) tightly coupled to the surrounding class/method/block, has a specific context (the surrounding class, method, and block).
new Thread() {
public void run() {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
System.out.println("Exception message: " + e.getMessage());
System.out.println("Exception cause: " + e.getCause());
}
}
}.start();
This is also one of the example for anonymous inner type using thread
An inner class is associated with an instance of the outer class and there are two special kinds: Local class and Anonymous class. An anonymous class enables us to declare and instantiate a class at same time, hence makes the code concise. We use them when we need a local class only once as they don't have a name.
Consider the example from doc where we have a Person class:
public class Person {
public enum Sex {
MALE, FEMALE
}
String name;
LocalDate birthday;
Sex gender;
String emailAddress;
public int getAge() {
// ...
}
public void printPerson() {
// ...
}
}
and we have a method to print members that match search criteria as:
public static void printPersons(
List<Person> roster, CheckPerson tester) {
for (Person p : roster) {
if (tester.test(p)) {
p.printPerson();
}
}
}
where CheckPerson is an interface like:
interface CheckPerson {
boolean test(Person p);
}
Now we can make use of anonymous class which implements this interface to specify search criteria as:
printPersons(
roster,
new CheckPerson() {
public boolean test(Person p) {
return p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25;
}
}
);
Here the interface is very simple and the syntax of anonymous class seems unwieldy and unclear.
Java 8 has introduced a term Functional Interface which is an interface with only one abstract method, hence we can say CheckPerson is a functional interface. We can make use of Lambda Expression which allows us to pass the function as method argument as:
printPersons(
roster,
(Person p) -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25
);
We can use a standard functional interface Predicate in place of the interface CheckPerson, which will further reduce the amount of code required.
i use anonymous objects for calling new Threads..
new Thread(new Runnable() {
public void run() {
// you code
}
}).start();
Anonymous inner class can be beneficial while giving different implementations for different objects. But should be used very sparingly as it creates problem for program readability.
One of the major usage of anonymous classes in class-finalization which called finalizer guardian. In Java world using the finalize methods should be avoided until you really need them. You have to remember, when you override the finalize method for sub-classes, you should always invoke super.finalize() as well, because the finalize method of super class won't invoke automatically and you can have trouble with memory leaks.
so considering the fact mentioned above, you can just use the anonymous classes like:
public class HeavyClass{
private final Object finalizerGuardian = new Object() {
#Override
protected void finalize() throws Throwable{
//Finalize outer HeavyClass object
}
};
}
Using this technique you relieved yourself and your other developers to call super.finalize() on each sub-class of the HeavyClass which needs finalize method.
You can use anonymous class this way
TreeSet treeSetObj = new TreeSet(new Comparator()
{
public int compare(String i1,String i2)
{
return i2.compareTo(i1);
}
});
Seems nobody mentioned here but you can also use anonymous class to hold generic type argument (which normally lost due to type erasure):
public abstract class TypeHolder<T> {
private final Type type;
public TypeReference() {
// you may do do additional sanity checks here
final Type superClass = getClass().getGenericSuperclass();
this.type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
}
public final Type getType() {
return this.type;
}
}
If you'll instantiate this class in anonymous way
TypeHolder<List<String>, Map<Ineger, Long>> holder =
new TypeHolder<List<String>, Map<Ineger, Long>>() {};
then such holder instance will contain non-erasured definition of passed type.
Usage
This is very handy for building validators/deserializators. Also you can instantiate generic type with reflection (so if you ever wanted to do new T() in parametrized type - you are welcome!).
Drawbacks/Limitations
You should pass generic parameter explicitly. Failing to do so will lead to type parameter loss
Each instantiation will cost you additional class to be generated by compiler which leads to classpath pollution/jar bloating
An Anonymous Inner Class is used to create an object that will never be referenced again. It has no name and is declared and created in the same statement.
This is used where you would normally use an object's variable. You replace the variable with the new keyword, a call to a constructor and the class definition inside { and }.
When writing a Threaded Program in Java, it would usually look like this
ThreadClass task = new ThreadClass();
Thread runner = new Thread(task);
runner.start();
The ThreadClass used here would be user defined. This class will implement the Runnable interface which is required for creating threads. In the ThreadClass the run() method (only method in Runnable) needs to be implemented as well.
It is clear that getting rid of ThreadClass would be more efficient and that's exactly why Anonymous Inner Classes exist.
Look at the following code
Thread runner = new Thread(new Runnable() {
public void run() {
//Thread does it's work here
}
});
runner.start();
This code replaces the reference made to task in the top most example. Rather than having a separate class, the Anonymous Inner Class inside the Thread() constructor returns an unnamed object that implements the Runnable interface and overrides the run() method. The method run() would include statements inside that do the work required by the thread.
Answering the question on whether Anonymous Inner Classes is one of the advantages of Java, I would have to say that I'm not quite sure as I am not familiar with many programming languages at the moment. But what I can say is it is definitely a quicker and easier method of coding.
References: Sams Teach Yourself Java in 21 Days Seventh Edition
The best way to optimize code. also, We can use for an overriding method of a class or interface.
import java.util.Scanner;
abstract class AnonymousInner {
abstract void sum();
}
class AnonymousInnerMain {
public static void main(String []k){
Scanner sn = new Scanner(System.in);
System.out.println("Enter two vlaues");
int a= Integer.parseInt(sn.nextLine());
int b= Integer.parseInt(sn.nextLine());
AnonymousInner ac = new AnonymousInner(){
void sum(){
int c= a+b;
System.out.println("Sum of two number is: "+c);
}
};
ac.sum();
}
}
One more advantage:
As you know that Java doesn't support multiple inheritance, so if you use "Thread" kinda class as anonymous class then the class still has one space left for any other class to extend.

Java instancing an interface results Odd behavior

I am just wandering if following is an odd behaviour.
public interface TestInterfaceTwo {
public void sayBye();
}
public interface TestInterfaceOne {
public void sayHI();
}
public abstract class TestIntefaceClass implements TestInterfaceOne, TestInterfaceTwo {
#Override
public void sayHI() {
System.out.println("HI");
}
#Override
public void sayBye() {
System.out.println("Bye");
}
}
public class InterfaceImplementer extends TestIntefaceClass{
#Override
public void sayHI() {
System.out.println("SAY HI");
}
}
public static void main(String[] args) {
InterfaceImplementer impl = new InterfaceImplementer();
TestInterfaceOne impl1 = new InterfaceImplementer();
TestInterfaceTwo impl2 = new InterfaceImplementer();
TestIntefaceClass impl3 = new InterfaceImplementer();
impl.sayHI();
impl.sayBye();
impl1.sayHI();
impl2.sayBye();
impl.sayBye();
impl3.sayBye();
impl3.sayHI();
}
These calls result the following
SAY HI
Bye
SAY HI
Bye
Bye
Bye
SAY HI
I needed to know if interface instances inherit only the expected behavior from the interface or if it inherits the abstract class. It seems it does the latter and I would like to know an explanation for this and if it is bug Or a feature. :)
This works as expected. I am not entirely sure what is that confuses you.
I needed to know if interface instances inherit only the expected behavior from the interface or if it inherits the abstract class. It seems it does the latter and I would like to know an explanation for this and if it is bug Or a feature. :)
Interfaces don't implement any 'behaviour' (although Java 8 provides default methods) and you can't instantiate one. All those instances you're creating are class instances - in your case, instances of InterfaceImplementer. So let's look at this class and its parent:
TestIntefaceClass implements two interfaces and their methods. Nothing special here.
InterfaceImplementer extends TestIntefaceClass class, it inherits the implementation of sayBye() but it provides its own implementation of sayHi().
Now the following (and the other similar examples from your code)
TestInterfaceOne impl = new InterfaceImplementer();
creates an instance of InterfaceImplementer, as you can see on the right hand side. Thus the implementations that will be used when calling sayHi() and sayBye() will be the ones that Interfaceimplementer overrides / inherits.
LE: This link will probably be useful to you. It discusses using interfaces as types, which is what you're doing.
the "new InterfaceImplementer()" is giving you exactly that ... its just you are decalring them as the various ways .... it's working as expected

Categories