I'm trying to use a method from another class, but I think I can't really use the constructor
here is the first class :
public class Rules {
public Rules(int size) {
//body
}
public void methodINeed() {
}
}
and I want to use the method in it in my second class,
but since if I use the constructor I have to give an int, which basically
screws up my calculations, i'm left with no idea of what to do,
what are my possibilities here?
just make another empty constructor:
public class Rules{
public Rules(int size){
//body
}
public Rules()
{
//body
}
public void methodIneed(){
}
}
Then to access the method you need,
Rules x = new Rules();
x.methodINeed();
You can access methods of other classes without contructing them if you declare those methods static:
public class Rules{
public Rules(int size){
//body
}
public static void methodIneed(){
}
}
I think you have to review the design of your classes why in the earth you have to call a method in other class for calculations purpose ???
possible solution:
mix two classes
add third class ( for instance Helper class) and call HelperClass.calculateForMe(sth)
Related
So I am a bit new to Java. I just got introduced to interfaces and i have to create a method that returns an instance of the interface Chassis
Below is the code:
public interface Chassis {
public String Chassis = "Chassis";
public static void main(String[] args) {
public String getChassisType() {
return Chassis;
}
The problem is, I keep getting error that abstract methods cannot have a body (as indicated by the blockquote) yet i had not declared my method as abstract.
What seems to be the problem?
You have two problems, You can't put a method inside another method, and you can't define a method like this in an interface in Java. In Java 8 you can do this
public interface Chassis {
String Chassis = "Chassis";
default String getChassisType(){
return Chassis;
}
}
I wouldn't define your public static void main inside an interface. While it is allowed now, most developers would find this confusing. See #Jürgen's answer, as this what most experienced developers would say I believe.
I would create another class like
public class Main {
public static void main(String... args) {
// an anonymous subclass so you have something to create/call.
System.out.println(new Chassis(){}.getChassisType());
}
}
An interface is a kind of abstract. It cannot be instantiated, It can have only declaration of methods and attributes not definition. You can only implement it in a class, if you do so in a class you must define all the methods which are declared in the interface. A main method need to be defined in order to execute the program. So it should not be placed inside an interface. change your code like this below
public interface chassis
{
String Chassis;
public String chassis();
}
public class example implements chassis
{
public String chassis()
{
Chassis="chassis";
return Chassis;
}
public static void main(String[] args)
{
System.out.println(new example().getChassisType());
}
}
This code would not work at all. A main method is only valid for classes, not for interfaces.
EDIT: as stated below the answer is not correct. But having a method inside a method still does not work. See the other answers.
I have a class with a method that takes a single parameter. This parameter is a nested class inside the mocked class, but it is private (And static but I don't think that makes much of a difference to this). How do I go about mocking this method?
Example:
public class myClass {
public anotherObject;
public myClass(AnotherObject anotherObject) {
this.anotherObject = anotherObject;
}
public void exec() {
//Some instructions ...
//This second method is inside another completely seperate class.
anotherObject.secondMethod(new NestedClass());
}
private static class NestedClass {
public NestedClass() {
//Constructor
}
//Variables and methods, you get the picture
}
}
In the above example secondMethod(...) is the method that I want to mock.
All attempts to find other examples of this problem just return results relating to mocking a single private nested class, or mocking static classes, which aren't completely relevant to this and don't seem to provide any work around that I can figure out.
EDIT:
I'm looking for some sort of solution that looks like this:
#Test
public void testExec() {
AnotherObject anotherObject = mock(AnotherObject.class);
when(anotherObject.secondMethod(any(NestedClass.class))).thenReturn(0);
MyClass testThisClass = new MyClass(anotherObject);
}
Notes: I'm not allowed to make modifications to the code I'm afraid, I am only allowed to create these tests to make sure the current implementation works later down the line when modification are made to it.
If I am understanding the requirement correctly, add one method say executeSecondMethod(). Call this method in your main method class.
public class myClass {
public void exec() {
//Some instructions ...
secondMethod(new NestedClass());
}
public void secondMethod(NestedClass example) {
//Some instructions that I want to just mock out...
}
private static class NestedClass {
//Variables and methods, you get the picture
}
public static executeSecondMethod(){
secondMethod(new NestedClass()); // pass the nested class object here
}
}
public class mainClass{
public static void main(){
executeSecondMethod();
}
}
I have a Java class with two constructors. There are a lot of methods within this class. Most of those methods will behave correctly regardless of which constructor is used, but a few will need to behave differently. Let's say methodA() is the latter, I could just recreate it and use two methods with different names, but that would mean refactoring a lot of code in the rest of the application and generally seems like a bad solution. Here's some code to demonstrate:
public class Example {
public Example(int x, int y) {}
public Example(int x){}
public methodA(){
//If the first constructor is called, this method needs to behave
//differently than if the second were called.
}
public methodB(){
//But I still want access to this method, which behaves the same regardless
}
My thought is to use nested classes, created two nested classes with different methodA()'s but having the same methodB() in the parent class. Is there a better way to implement what I desire or am I on the right track?
Many thanks.
A classic inheritance should suit your needs:
public class SuperExample {
public SuperExample(int x) {
}
public void methodA() {
}
public void methodB() {
}
}
public class SubExample extends SuperExample {
public SubExample(int x, int y) {
super(x);
}
#Override
public void methodA() {
}
}
Sounds like you want to apply polymorphism here. Create a parent class with all the common methods and subclass that one to create the different behavior. Instantiation could happen via a factory (maybe look up factory pattern if you're not sure) depending on the parameters.
At present I have a class that is calling the static method of a different class. What I am trying to do however is have the static method change a variable of the calling class, is that possible?
Example code:
public class exClass {
private int aVariable;
public exClass() {
othClass.aMethod();
}
}
public class othClass {
static void aMethod() {
// stuff happens, preferably stuff that
// allows me to change exClass.aVariable
}
}
So what I would like to know is, if there is a way to access aVariable of the instance of exClass that is calling othClass. Other than using a return statement, obviously.
Not if aClass doesn't expose that variable. This is what encapsulation and information hiding are about: if the designer of the class makes a variable private, then only the component that owns it can modify or access it.
Of course, the dirty little secret in Java is that reflection can get you around any private restriction.
But you should not resort to that. You should design your classes appropriately and respect the designs of others.
You can pass this as a parameter to the second function.
public class exClass {
public int aVariable;
public exClass()
{
othClass.aMethod(this);
}
}
public class othClass{
static void aMethod(exClass x)
{
x.aVariable = 0; //or call a setter if you want to keep the member private
}
}
you should gave the static method in othClass the instance of exClass like othClass.aMethod(this), then you can change the variable of that instance, or make the variable static if you dont need an instance
in a class i have
A a = new A(){
stuffhere
};
now i found that i need to create the new A inside a method and return it, but i have to define the stuffhere from the class caller. Is there a way in java to do so? Something like
A a = createAClass(){
stuffhere
};
public A createAClass()[T]{
return new A(){T};
}
or something similar. I would prefer not to use an interface to pass to the create method, since my anonymous classes not only override methods, but also adds attributes and new functions, and i don't think i can pass them with an interface..
Any thought?
EDIT for the -1ers (a simple comment would suffice)
with the syntax [T], obviously wrong, i meant something that can pass a generic code, let's say a copy-paste of code.
createAClass()[int a; String b; #override public void mymethod(){dosomethigb;} public void dosomethingelse(){dosomethingelse;}];
would work like
public A createAClass(){
return new A()
{
int a;
String b;
#override public void mymethod()
{dosomethigb;}
public void dosomethingelse()
{dosomethingelse;}};
};}
but if i write in another part of the program
createAClass()[float c; List d; public void yourmethod(){dosomething2;} #override public void dosomethingelse(){dosomethingelse2;}];
it would instead work like
public A createAClass(){
return new A()
{
float c;
List d;
public void yourmethod()
{dosomething2;}
#override public void dosomethingelse()
{dosomethingelse2;}
};}
My bad, i choose a bad may of making an example, but i thought it was the clearest way. Maybe i should have used X instead of T?..
Long story short:
i want create an anonymous class inside a method, but define what the anonymous class does in the method caller, and not inside the method(like the title says)
EDIT2:
i know i can't access the new methods from the class, what i do now is create an anonymous class, add a few attributes and method, and then use them in an overridden method. The added methods are not a problem, since i can make the method caller to pass an interface that is called by the overridden method in the anonymous class created, the problems are the attributes. I don't know how to add them in the anonymous class passing them from the method caller.
Something like the following usually works:
public A createAClass(final String value){
return new A(){
// some code here that can access value
};
}
If you are looking for something else, please clarify the question.
Edit
Answer is no you can't do that. You are trying to create an A with no defined API for A. Even if you could do what you propose, how would any user of A know what methods / fields are available if A is not defined somewhere? For A to be useful, you need to have an API that A implements.
Not sure whether fully understood by me. But the pattern is like this:
public class Here {
private int stuff;
public class A {
private A() { ... }
... ++stuff; ...
}
public A createA() { ... }
}
...
Here here = ...
A a = here.createA();
AFTER QUESTION EDITED:
The simplest way is to override a method:
final Object stuff = ...;
A a = new A() {
#Override
protected void onSomeEvent() {
... stuff.toString();
}
}
Then A can call onSomeEvent.