Cheers, I am pretty new to java and I and I have ran across a problem
I have three classes, all inheriting things between them. Starting I have a class A:
public class A{
private int index;
public A(int index) {
System.out.println("Creating an instance of A");
this.index = index;
}
}
then I have a sublass of A, class M which has a enum inside as:
public class M extends A{
public enum Letter {
A,B,C;
}
private Letter letter;
public M(int index, Letter aLetter) {
super(index);
System.out.println("Creating an instance of M");
this.letter = aLetter;
}
}
and finally a last class P , subclass of M:
public class P extends M {
private T t;
public enum T{
o,
a,
t
}
public P(int index, Letter aLetter, T aT) {
super(index,aLetter);
System.out.println("Creating an instance of P");
this.t = aT;
}
}
What I want to do is create e.g. 3 objects of the class P, and pass on to them RANDOMLY a value of each of these enums. I thought of creating a function in the main class which would be kind of like:
Letter getRandLetter() {
Random rand = new Rand();
int pick = rand.nextInt(M.Letter.values().length);
if (pick == 0) {
return Letter.A;
} else if (pick == 1) {
return Letter.B;
} else {
return Letter.C;
}
}
my main looks like this:
int N = 3;
M[] new_m = new M[N]
for(int i = 0; i < N; i++) {
new_m[i] = new P(i, getRandLetter(), getRandT());
}
however I get this error: Cannot make a static reference to the non-static method . What Can I do to achieve what I want?
The error is telling what to do:
Cannot make a static reference to the non-static method
Your main method is static, and the methods called from it should be static as well. So your getRandLetter() and getRandT() methods should be static.
getRandLetter() should look like this:
static Letter getRandLetter() {
Random rand = new Rand();
int pick = rand.nextInt(M.Letter.values().length);
if (pick == 0) {
return Letter.A;
} else if (pick == 1) {
return Letter.B;
} else {
return Letter.C;
}
}
And getRandT() should be static as well.
Related
I am having hard time to understand the solution of the given question. I can't understand at each step which of the class' methods are invoked.
I tried to make a list for what are a,b,c declared types and actual types then try to chose overridden or overloaded methods but it is complex.
class Upper {
private int i;
private String name;
public Upper(int i) {
name = "Upper";
this.i = i;
}
public void set(Upper n) {
i = n.show();
}
public int show() {
return i;
}
}
class Middle extends Upper {
private int j;
private String name;
public Middle(int i) {
super(i + 1);
name = "Middle";
this.j = i;
}
public void set(Upper n) {
j = n.show();
}
public int show() {
return j;
}
}
class Lower extends Middle {
private int i;
private String name;
public Lower(int i) {
super(i + 1);
name = "Lower";
this.i = i;
}
public void set(Lower n) {
i = n.show();
}
public int show() {
return i;
}
}
class Tester {
public static void main(String[] args) {
Lower a = new Lower(1);
Middle b = a;
Upper c = new Middle(5);
a.set(c);
b.set(a);
c.set(b);
System.out.println(a.show());
System.out.println(b.show());
System.out.println(c.show());
}
}
What is printed as a result of System.out.println(a.show()); after the set commands? Answer is 1
What is printed as a result of System.out.println(b.show()); after the set commands? Answer is 1
What is printed as a result of System.out.println(c.show()); after the set commands? Answer is 1
I don't get why the answers of all these are 1. Also I can't tell which class' overridden or overloaded methods that "a.set(c); b.set(a); c.set(b);" uses. A detailed explanation would be really helpful.
a.set(c) uses the set-method from Middle, as that overrides the one from Upper and the (overloaded) set from Lower is not applicable because c is not an instance of Lower.
Therfore j is set to c.show() which returns c's attribute j, so it will be set to 5. Consequently the (Lower-)attribute i of a is never touched and remains at 1 when it is shown and printed.
Try to resolve the others yourself.
So I've seen, in many places, calling methods of a class like:
SomeClass obj = new SomeClass();
obj.addX(3).addY(4).setSomething("something").execute();
I don't think I completely understand how that works. Is each method independent of each other, so the above is equal to:
obj.addX(3);
obj.addY(4);
obj.addSomething("something");
obj.execute();
Or are they designing their class structure in some other fashion that allows for this. If they are how are they designing their classes to support this?
Also, does that have a specific name? Or is this just calling methods on a class?
That would be method chaining. It can do one of two things.
Each call to a method returns this which allows you to continue to call methods on the original instance.
public class SomeClass
{
private int _x = 0;
private int _y = 0;
private String _something = "";
public SomeClass addX(int n)
{
_x += n;
return this;
}
public SomeClass addY(int n)
{
_y += n;
return this;
}
public SomeClass setSomething(String something)
{
_something = something;
return this;
}
// And so on, and so on, and so on...
}
Each method call returns a new instance of the class with everything copied/updated appropriately. This makes the class immutable (so you don't accidentally modify something that you didn't mean to).
public class SomeClass
{
private int _x = 0;
private int _y = 0;
private String _something = "";
public SomeClass(int x, int y, String something)
{
_x = x;
_y = y;
_something = something;
}
public SomeClass addX(int n)
{
return new SomeClass(_x + n, _y, _something);
}
public SomeClass addY(int n)
{
return new SomeClass(_x, _y + n, _something);
}
public SomeClass setSomething(String something)
{
return new SomeClass(_x, _y, something);
}
// And so on, and so on, and so on...
}
Some people have also mentioned Fluent Interfaces. Fluent Interfaces utilize method chaining to create an API that provides something along the lines of a Domain Specific Language which can make code read much more clearly. In this case, your example doesn't quite qualify.
they modify object's state and return the same object back mostly
class Number{
int num;
public Number add(int number){
num+=number;
return this;
}
}
you can call it like
new Number().add(1).add(2);
most of the time the use case is to return new Object to support immutability
Each of those methods return an instance. For example, the call to
obj.addX(3)
will return the same instance obj, so the call
obj.addX(3).addY(4)
will be equivalent to
obj.addY(4)
This is called method chaining.
The methods are implemented like this:
public SomeClass addX(int i) {
// ...
return this; // returns the same instance
}
public class Test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Test1 abc = new Test1();
abc.add1(10, 20).sub1(40, 30).mul1(23, 12).div1(12, 4);
}
public Test1 add1(int a, int b)
{
int c = a + b;
System.out.println("Freaking Addition output : "+c);
return this;
}
public Test1 sub1(int a, int b)
{
int c = a - b;
System.out.println("Freaking subtraction output : "+c);
return this;
}
public Test1 mul1(int a, int b)
{
int c = a * b;
System.out.println("Freaking multiplication output : "+c);
return this;
}
public Test1 div1(int a, int b)
{
int c = a / b;
System.out.println("Freaking divison output : "+c);
return this;
}
}
I have a class Game that is my main class and a second class Card.
Class Card hast its properties and constructor private, only function init is public.
Function init checks values for plausibility and if everything is fine than the constructor gets the values and creates an object.
Now I wannt in class Game to create an object from class Card.
How should I do this?
Here is my code:
Class Game:
import java.util.List;
import java.util.Vector;
public class Game {
public static void main(String[] args)
{
/*
CREATING NEW CARD OBJECT
*/
int value = 13;
Vector<Card> _card_set = new Vector<Card>();
for (int i = 2; i < 54; i++)
{
if(--value == 0)
{
value = 13;
}
Card _myCard;
_myCard.init(i,value);
}
}
}
Class Card:
public class Card {
private int index;
private int value;
private String symbol;
/*
CREATING A PLAYCARD
*/
private Card(int index,int value)
{
this.index = index;
this.value = value;
value = (int) Math.floor(index % 13);
if(this.index >= 2 && this.index <= 14)
{
this.symbol = "KARO";
}
else if (this.index >= 15 && this.index <= 27)
{
this.symbol = "HERZ";
}
else if (this.index >= 26 && this.index <= 40)
{
this.symbol = "PIK";
}
else if (this.index >= 41 && this.index <= 53)
{
this.symbol = "KREUZ";
}
System.out.println("Card object wurde erstellt: " + symbol + value);
System.out.println("------<><><><>------");
}
/*
SHOW FUNCTION
GET DETAILS ABOUT PLAYCARD
*/
public String toString()
{
return "[Card: index=" + index + ", symbol=" + symbol + ", value=" + value + "]";
}
/*
Initialize Card object
*/
public Card init(int index, int value)
{
/*
Check for plausibility
if correct constructor is called
*/
if((index > 1 || index > 54) && (value > 0 || value < 14))
{
Card myCard = new Card(index,value);
return myCard;
}
else
{
return null;
}
}
}
You should define your init method as static, implementing the static factory method that Braj talks about. This way, you create new cards like this:
Card c1 = Card.init(...);
Card c2 = Card.init(...);
...
As #Braj mentioned in comments, you can use static factory. Private constructor cannot be accessed outside of class, but it can be accessed from inside, like the following:
public class Test
{
private Test(){
}
static Test getInstance(){
return new Test();
}
}
This pattern can be used for making Builders, for example.
Note :
You can access private constructor from within the class itself as in a public static factory method.
You can access it from the enclosing class it its a nested class.
public class demo
{
private demo()
{
}
public static demo getObject()
{
return new demo();
}
public void add()
{
}
}
class Program
{
static void Main(string[] args)
{
demo d1 = demo.getObject();
d1.add();
}
}
I would say don't make the constructor private, don't make the build code under the constructor (place it in a new method, which can be private) and make a method to return the card outside the class.
Then use the card object and call the method to retrieve your card from the Card class, make sure to declare the type Card and make sure that the method returns properly.
Class<?> class = Class.forName("SomeClassName");
Constructor<?> constructor = class.getConstructors[0];
constructor.setAccessible(true);
To convert the privately declared constructor to the public one till program execution. Also, this concept is related to Reflection API.
Object o = constructor.newInstance();
if(o.equals(class)) {
System.out.println("Object for \"SomeClassName\" has been created");
}
Imagine I have a class
class A {
int a;
int b;
A(int a, int b) {
this.a=a; this.b=b;
}
int theFunction() {
return 0;
}
void setTheFunction([...]) {
[...]
}
}
And for every new object I instantiate, I want to be able to define theFunction() in a new way by calling setTheFunction( [...] ). For example, I want to do something like this:
A test = new A(3,2);
test.setTheFunction ( int x = a*b; return x*x+2; );
System.out.println(test.theFunction()); // Should return (3*2)*(3*2)+2 = 38
Or something like this:
A test2 = new A(1,5);
test.setTheFunction ( for(int i=0; i<b; i++) a=a*b*i; return a; );
Now, what I could of course do is write all of those functions inside class A and use a switch statement to determine which one is to pick. But if I don't want the algorithm of theFunction() hardcoded inside my class A, is there any way to do something similar to the above? And what would setTheFunction() look like? What type of argument would you have to pass?
You can use Callable.
public class A<V> {
public int a;
public int b;
private Callable<V> callable;
public A(int a, int b) {
this.a = a;
this.b = b;
}
public V theFunction() {
try {
return callable.call();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void setTheFunction(Callable<V> callable) {
this.callable = callable;
}
}
Then, to use it:
final A<Integer> test = new A<Integer>(3, 2);
test.setTheFunction(new Callable<Integer>() {
int x = test.a * test.b;
return x * x + 2;
});
System.out.println(test.theFunction());
Of course, the generic typing of A isn't necessary, but I've added it to make this answer to be less restricted.
If you always need to operate on the same arguments, you could solve this by defining an interface such as:
public interface MethodPerformer {
int performOperation(int a, int b);
}
Then pass in implementations of this to your setTheFunction method. Finally, invoke the operation when you call the other method:
class A {
int a;
int b;
MethodPerformer performer;
A(int a, int b) {
this.a=a; this.b=b;
}
int theFunction() {
performer.performOperation(a, b);
}
void setTheFunction(MethodPerformer performer) {
this.performer = performer;
}
}
Clearly additional code would be required to check the performer is not null. Perhaps take a performer in the constructor?
Instead of using a setter, the more natural way is to use an anonymous sub-class. This way the compiler will check it behaves correctly and has access to the right variables.
public class Main {
static abstract class A {
protected int a, b;
A(int a, int b) {
this.a = a;
this.b = b;
}
public abstract int theFunction();
}
public static void main(String... ignored) {
A test = new A(3, 2) {
#Override
public int theFunction() {
int x = a * b;
return x * x + 2;
}
};
System.out.println(test.theFunction()); // Should return (3*2)*(3*2)+2 = 38
A test2 = new A(1, 5) {
#Override
public int theFunction() {
for (int i = 1; i < b; i++) a = a * b * i;
return a;
}
};
System.out.println(test2.theFunction());
}
}
prints
38
15000
With this you can solve any kind of problem, that involves any kind of public variable of A (but can work with package private variables as well, if the AFunction implementation resides in the same package), that a function may use to perform it's operation. It's just not as compact as it can be in other languages than java.
interface AFunction
{
int call(A a);
}
class A
{
int a;
int b;
//giving it a default implementation
private AFunction f = new AFunction()
{
#Override
public int call(A a)
{
return a.a * a.b;
}
};
A(int a, int b)
{
this.a = a;
this.b = b;
}
int theFunction()
{
return f.call(this);
}
void setTheFunction(AFunction f)
{
this.f = f;
}
}
By the way as AlexTheo points out, all answers so far (except for Peter Lawrey's) are a form of the strategy design pattern.
The easiest way to do this is defining "A" as an interface instead of a class. You declare theFunction() without actually implementing it.
In client code, everytime you need "A", you instantiate a so-called anonymous inner class.
For example:
new A() { #Override public int theFunction() { ...your implementation... } };
I have the following code and it will not compile.
public class P {
private int num;
P(int n) {
this.num = n;
}
}
public class Q extends P {
private int i;
public Q() {
i = 0;
}
}
Fix the second method so that it can compile.
Invoke the super constructor:
public Q() {
super(42); // <--
i = 0;
}
You can read more about super here.
You need to add default constructor in P to make it compile
P() {
this.num = 0; // some default value
}
In the code the compiler write the super() keyword in the Q class that time control will go the P class and it call the constructor, but P class has a parameter constructor.so you can add super() keyword with the any number because P class constructor has a parameter of int type.
class P {
private int num;
P(int n) {
this.num = n;
}
}
public class Q extends P {
private int i;
public Q() {
super(20);
i = 0;
}
}