How would I be able to accomplish the following:
public class testClass implements Interface {
public testClass(Interface[] args) {
}
}
So that I could declare
Interface testObject = new testClass(new class1(4), new class2(5));
Where class1 and class2 are also classes that implement Interface.
Also, once I accomplish this, how would I be able to refer to each individual parameter taken in to be used in testClass?
Thanks :)
So that I could declare
Interface testObject = new
testClass(new class1(4), new
class2(5));
You need to use varargs in testClass constructor:
public testClass (Interface ... args) {
for (Interface i : args) {
doSmthWithInterface (i);
}
}
You can use varargs, which are treated as arrays. For example:
public testClass(Interface... args) {
System.out.println(args[0]);
}
Like this (save the whole sample into a file, say testClass.java):
interface Interface{}
public class testClass implements Interface
{
public testClass(Interface ... args)
{
System.out.println("\nargs count = " + args.length);
for( Interface i : args )
{
System.out.println( i.toString() );
}
}
public static void main(String[] args)
{
new testClass(
new Interface(){}, // has no toString() method, so it will print gibberish
new Interface(){ public String toString(){return "I'm alive!"; } },
new Interface(){ public String toString(){return "me, too"; } }
);
new testClass(); // the compiler will create a zero-length array as argument
}
}
The output will be as follows:
C:\temp>javac testClass.java
C:\temp>java testClass
args count = 3
testClass$1#1f6a7b9
I'm alive!
me, too
args count = 0
You don't have to use varargs, you can use an array as an input parameter, varargs is basically just a fancy new syntax for an array parameter, but it will help prevent you from having to construct your own array in the calling class.
i.e. varargs allow (parm1, parm2) to be received into an array structure
You cannot use an interface to enforce a Constructor, you should probably use a common abstract super class with the desired constructor.
public abstract class Supa {
private Supa[] components = null;
public Supa(Supa... args) {
components = args;
}
}
public class TestClass extends Supa {
public TestClass(Supa... args) {
super(args);
}
public static void main(String[] args) {
Supa supa = new TestClass(new Class1(4), new Class2(5));
// Class1 & Class2 similarly extend Supa
}
}
Also see the composite design pattern http://en.wikipedia.org/wiki/Composite_pattern
Related
I have code like
public class Functionz {
public static boolean test() {
return true;
}
public static void main(String[] args) {
Function[] funcs = new Function[] {test}; // and others
for (Function func : funcs) {
func();
}
}
}
and my error is: cannot find symbol: test in the line with the function array declaration.
Hope this isn't a stupid question, very new to java, not new to object oriented languages like python and C++.
A Function in Java does takes one parameter as input and one as output.
You might declare parameter's type this way : Function<Integer, String> is a function that transforms an Integer into a String
Your method test() does not take any input value and outputs a boolean so it's a Supplier.
import java.util.function.Supplier;
public class Main {
public static boolean test() {
System.out.println("lorem ipsum");
return true;
}
public static void main(String[] args) {
Supplier[] funcs = new Supplier[] {Main::test}; // and others
for (Supplier func : funcs) {
func.get();
}
}
}
Your code would compile if test requires one (and only one parameter) like
import java.util.function.Function;
public class Main {
public static boolean test(String str) {
System.out.println(str);
return true;
}
public static void main(String[] args) {
Function[] funcs = new Function[] {(Object anyObject) -> test(anyObject.toString())}; // and others
for (Function func : funcs) {
func.apply("lorem ipsum");
}
}
}
Here's the list of those types
Please note that Function doesn't type its parameters in construction because you can't create arrays with generic type in Java (you might for specific usecases) => Use a List will help you here
I'm java virgin. I've made really simple code like below.
class TreeData implements Comparable<TreeData> {
private String sixString;
private ArrayList<Integer> stringNum = new ArrayList<Integer>();
private ArrayList<Integer> charNum = new ArrayList<Integer>();
public TreeData(String sixString, int stringNum, int charNum){
this.sixString = sixString;
(this.stringNum).add(stringNum);
(this.charNum).add(charNum);
}
public int compareTo(TreeData other) {
return sixString.compareTo(other.getSixString());
}
public String getSixString(){
return sixString;
}
}
class Child<T extends Comparable<T>>{
public void print(T data){
//error : String a = data.getSixString();
System.out.println("hi");
}
}
public class Test {
public static void main(String[] args) {
Child<TreeData> child = new Child<TreeData>();
TreeData td = new TreeData("sixString", 8, 2);
child.print(td);
}
}
I had a problem in 'print' method in the Child class. When I tried calling the getSixString() method of data(passed as argument), it occurs error. I don't know why I can't using public method in the argument 'data'. Is it related with Generic? Thanks, in advance.
In your Child class, you only define T to be extending Comparable. Yet you expect it to have the method getSixString which Comparable doesn't have. What you probably want it for it to be extending TreeData:
class Child<T extends TreeData>{
public void print(T data){
String a = data.getSixString();
//should work now since T defines getSixString()
}
}
Or better yet if all you want is for T to be TreeData, you don't need any generic class. I'm assuming your real intention was:
class Child extends TreeData {
public void print(){
String a = getSixString();
}
}
i'm trying to write anonymous inner class
interface Face{
void seeThis(String what);
}
class Eyes {
public void show(Face f){}
}
public class Seen {
public void test() {
Eyes e = new Eyes();
e.show(new Face() {
#Override
public void seeThis(String what){
System.out.print(what);
}
});
public static void main(String[] args) {
Seen s = new Seen();
s.test();
}
}
How to call seeThis() and how to pass parameter to it?
Method seeThis() belongs to Face class, which instance is anonymous and thus cannot be reached without storing reference to it. If you want to store a reference, you can do this in the following way:
public class Seen {
public Face face;
....
this.face = new Face() { ... };
e.show(this.face);
And then,
Seen s = new Seen();
s.face.seeThis();
Now, regarding passing the parameter. You have two options - declare parameter outside of anonymous class and make it final in order to be reachable by this anonymous class, or replace anonymous class with normal one and pass the parameter to its constructor:
Approach one:
final int parameter = 5;
...(new Face() {
#Override
public void seeThis() {
System.out.println(parameter);
}
});
Approach two:
public class MyFace implements Face() {
private final int parameter;
public MyFace(int parameter) {
this.parameter = parameter;
}
#Override
public void seeThis() {
System.out.println(parameter);
}
}
Then,
...
e.show(new MyFace(10));
I want to create an object using a method but I want it (object+reference) to live even after the method ends. Example of code:
public class start{
public static void main (String [] Args){
public void createObject(){
object1 createdObject = new object1();
}
createObject();
createdObject.doSomething();
}
}
public class object1{
//code for object 1
}
So my main question is: how to create object using method and let it live even after method ends. The problem is that reference createdObject is popped of stack after method ends and therefore I can't use it anymore. Is it even possible to create object for further use this way?
public class start{
public static void main (String [] Args){
//class level scope
object1 createdObject = null;
private void createObject(){
createdObject = new object1();
}
}
public class object1{
//code for object 1
}
NOTE: I have not following naming conventions. But please follow them in actual code
UPDATE: Proper code check it out
public class Main {
public static void main(String[] args) {
new MyClass().doSomething();
}
}
class MyClass{
Object obj ;
public void doSomething(){
createObject();
}
private void createObject(){
obj = new Object();
System.out.println("Created MyClass instance");
}
}
Your method should return object1 instead of void and you have to add the following line at the end of the method:
return createdObject;
I have a class with some constructors like this:
public MyClass(Control caller, WritableList elements, String pattern) {
this(caller, elements, pattern, new LabelProvider());
}
public MyClass(Control caller, WritableList elements, String pattern, ILabelProvider labelProvider) {
super(caller.getShell(), labelProvider);
// ...
}
public MyClass(Control caller, Collection<String> elements, String pattern) {
super(caller.getShell(), new LabelProvider());
// ...
}
If I try to create an instance of it using this:
new MyClass(getControl(), getWritableList(), "test");
or this:
new MyClass(getControl(), (WritableList) getWritableList(), "test");
Eclipse is complaining that the constructor is ambiguous. If I do this however:
new MyClass(getControl(), (Collection<SomeType>) getWritableList(), "test");
everything is fine. I was wondering what could be the problem? I'm using org.eclipse.core.databinding.observable.list.WritableList which comes with the RCP framework.
Edit:
I thought that WritableList extending the Collection interface could be the error but I created some test classes and it turned out that it is not the case:
public class Main {
/**
* Main.
* #param args
*/
public static void main(String[] args) {
TestClass obj = new TestClass(getTypeAInstance(), "asd");
}
public static SomeTypeA getTypeAInstance() {
return new SomeTypeA();
}
public static interface SomeInterface<T> {
}
#SuppressWarnings("rawtypes")
public static interface SomeInterfaceExtensionWithoutTypeParam extends SomeInterface {
}
public static interface SomeInterfaceExtensionWithTypeParam<T> extends SomeInterface<T> {
}
#SuppressWarnings("rawtypes")
public static interface SomeIntermediateInterface extends SomeInterfaceExtensionWithoutTypeParam, SomeInterfaceExtensionWithTypeParam {
}
public static class SomeTypeA implements SomeIntermediateInterface {
}
public static class TestClass {
public TestClass(SomeInterface<String> i, String s) {
}
public TestClass(SomeTypeA a, String s) {
}
}
}
It seems that the problem was with Eclipse's own Java compiler.