Trying to move my object initialisation and method calls out of my Main method - methods

I am trying to move some code out of the main method and use it in another class. The reason for doing this is that I learnt it was advised convention to do so and I am relatively new to Java so looking to try it out. Currently when I move the code into the 'Game' class I cannot resolve the errors that eclipse is showing.
Any help would be appreciated.
Main method in playGame class-
public class playGame {
public static void main(String[] args) {
// TODO Auto-generated method stub
player playerOne = new player();
GameHelper gameHelper = new GameHelper();
wordManipulator thisWord = new wordManipulator();
gameHelper.showDisplay();
playerOne.setPlayerName();
gameHelper.showIntro(playerOne.getPlayerName());
thisWord.showHiddenWord();
playerOne.setPlayerGuess();
}
}
The Game class
public class Game {
//other code for the game logic
}

Make sure to put your code in a method in the Game class, and then call that specific method.
Another hint : use capitals for class names.

Related

Inheriting default methods with the same name in the class without any compilation error

How a class can implement two interfaces with the same default method in Java 8.
I was not able to get the concept behind the same default method from different interfaces getting inherited in the sub class.Please explain the issue.
interface House {
default String getAddress() {
return "101 Main Str";
}
}
interface Bungalow extends House {
default String getAddress() {
return "101 Smart Str";
}
}
class MyHouse implements Bungalow, House {
}
public class TestClass {
public static void main(String[] args) {
House ci = new MyHouse(); //1
System.out.println(ci.getAddress()); //2
}
}
In the above code default method getAddress() in interface House is present.another method with the same name is declared as default in the extending interface Bungalow
How class MyHouse can implement both the interfaces without any compilation error(because it doesn't know which method has the preference in that case implementing should fail.)
If i call new MyHouse().getAddress(); gives compile error but it should give compilation error even without method calling from MyHouse class.
It seems that the answer is here, where there is a different example, but sort of makes sense and is really close to yours.
Ask me the exact same thing in 1/2 a year and I'll say it will fail at compile time and point me to this answer, so that I could read the JLS again. I guess this is how they decided to implement it. Without thinking too much, I, personally (may be wrong) think that this is at least counter intuitive...

Libgdx, Why Should I Use Constructors When Switching Screens?

I am a beginner in libgdx and was wondering in what cases you would need to use a constructor when switching screens (examples would be helpful). Is it to save memory? Also, is it better to create instances of all the screens in the main class that extends the game?
Here is an example of instances from https://code.google.com/p/libgdx-users/wiki/ScreenAndGameClasses :
public class MyGame extends Game {
MainMenuScreen mainMenuScreen;
AnotherScreen anotherScreen;
#Override
public void create() {
mainMenuScreen = new MainMenuScreen(this);
anotherScreen = new AnotherScreen(this);
setScreen(mainMenuScreen);
}
}
The constructor is in the next class:
public class MainMenuScreen implements Screen {
MyGame game; // Note it's "MyGame" not "Game"
// constructor to keep a reference to the main Game class
public MainMenuScreen(MyGame game){
this.game = game;
}
...
You should avoid creating all screens in Game class in create() method (you will allocate much memory at once and pointlesly). Create only one screen at a time when do you need It. So e.g. you click button New game in menu and there you call game.setScreen(new NextScreen(this));
You do not have to make constructor with Game parameter - but you will not have reference to the main Game class. Having reference to main game class is good for changing screens, method setScreen(screen).
You need the constructor because your changing to a screen that doesnt extend the Game class which is what u need to call setScreen(); Since ur passing the game class to the constructor you can use it to get back to the screen you were at (or another screen) without creating another class that extends Game
I prefer using a singleton.
Something like
public class MyGame extends Game {
private static MyGame myGame;
public static MyGame getInstance() {
if (myGame == null) {
myGame = new MyGame();
}
return myGame;
}
#Override
public void create() {
setScreen(new MainMenuScreen();
}
}
And the example for desktop main class
public class Main {
public static void main(String[] args) {
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
cfg.width = 800;
cfg.height = 480;
new LwjglApplication(MyGame.getInstance(), cfg);
}
}
Now whenever you need to change your screen use MyGame.getInstance().setScreen(new ScreenName());

Calling a variable from a void method

Hey this is a very simple question. Can I call a variable, in this case an array, from a void method? I have declared my arrays at the class level and initialized them in a void method. Not sure it I am doing this correctly but I am trying to call the array from another class. I am a beginner. Thank you for the help.
ex:
public class HeyThere{
public double me[];
public void yeahYou(int you){
me = new me[69]
}
}
Here you declarate a public variable (array)
public double me[ ];
and here you instantiate it in a method
me = new me[69]
Yes, since your class level array me is scoped as Public, you will be able to access it from another class after you instantiate the HeyThere class.
Ex:
public class HeyThereCaller
{
..
....
public void SomeMethod()
{
...
....
HeyThere heyThereInstance = new HeyThere();
double[] meArray = heyThereInstance.me;
}
}
HeyThere obj1; double a = obj1.me[0]; This is going to give an error in Java though, because me is not instantiated
Yes, you certainly can! Because me is public, you can access it from outside of the class in which it is stored.
Also, you spoke of accessing it from a void method. The return type of a method has no effect on the data it can access; void only means that the method doesn't return a value when called.
If you want to study how variables can be accessed in Java, there is some useful info on this page.

How to call private method by other methods?

I am confused of calling a private method by another method(public) belonging to the same class.Once I have been told I gotta create an object of that class and then call the private method via this object but in one of my questions in this forum I have been told that I dont need to use object.
public class Train() {
private void method1{......method definition..... }
public void method2{......how to invoke method1??}
}
Can I simply call the first method inside the second method by using method1(); or should I invoke it by creating an object of the class and Object_of_Train.method1();.
Which one should I use?
Within the class you should be able to call method1();
Outside the class you will need to call it from an instance of that class and will have access to public methods only
Use this.method1(); to call from method2() or any other non-static method in the class.
You can access the private methods of a class using java reflection package.
**Step1 − Instantiate the Method class of the java.lang.reflect package by passing the method name of the method which is declared private.
Step2 − Set the method accessible by passing value true to the setAccessible() method.
Step3 − Finally, invoke the method using the invoke() method.**
Example
import java.lang.reflect.Method;
public class DemoTest {
private void sampleMethod() {
System.out.println("hello");
}
}
public class SampleTest {
public static void main(String args[]) throws Exception {
Class c = Class.forName("DemoTest");
Object obj = c.newInstance();
Method method = c.getDeclaredMethod("sampleMethod", null);
method.setAccessible(true);
method.invoke(obj, null);
}
}
Source : Tutorialpoint

Need help converting PRISM Unity Module Init to PRISM MEF Module Init

I need help converting the following class for use in a program that I am developing. The original was a demo program from IdeaBlade called "PRISM EXPLORER" based on Unity. I need help converting one part from UNITY to MEF. I handled everything else. Just stuck on this one. I already marked my classes with the MEF "[EXPORT(typeof(XXX))]" and I think I need to use the "ComposeExportedValue" somehow. The confusing part is finding the equivelant for this line:
var provider =
(IEntityManagerProvider) _container.Resolve<IPersistenceGateway>();
_container.RegisterInstance<IEntityManagerProvider>(provider);
THANKS!
The following is the entire class I need to convert. You can find the original here: Ideablade PRISM Page
using Microsoft.Practices.Composite.Modularity;
using Microsoft.Practices.Composite.Regions;
using Microsoft.Practices.Unity;
using PrismExplorer.Infrastructure;
namespace ModelExplorer.Explorer {
public class ExplorerModule : IModule {
private readonly IUnityContainer _container;
public ExplorerModule(IUnityContainer container) {
_container = container;
}
public void Initialize() {
InitializeContainer();
SetViews();
}
// ToDo: Consider getting from configuration
private void InitializeContainer() {
RegisterGatewayAndEntityManagerProvider();
_container.RegisterType<IQueryRepository, QueryRepository>(
new ContainerControlledLifetimeManager()); // singleton
}
private void RegisterGatewayAndEntityManagerProvider() {
_container.RegisterType<IPersistenceGateway, PrismExplorerPersistenceGateway>(
new ContainerControlledLifetimeManager()); // singleton
var provider =
(IEntityManagerProvider) _container.Resolve<IPersistenceGateway>();
_container.RegisterInstance<IEntityManagerProvider>(provider);
}
private void SetViews() {
var regionManager = _container.Resolve<IRegionManager>();
var view = _container.Resolve<ExplorerView>();
regionManager.AddToRegion(RegionNames.MainRegion, view);
regionManager.RegisterViewWithRegion(RegionNames.MainRegion, typeof(ExplorerView));
}
// Destructor strictly to demonstrate when module is GC'd
//~MevModule() {
// System.Console.WriteLine("Goodbye, MevModule");
//}
}
}
The two corresponding methods on a CompositionContainer are ComposeExportedValue<T>(...), which allows you to add a specific instance to the container, and GetExportedValue<T>(...) which gets an instance of T from the container.
If you can design your types in a way to reduce this use of service location and try and prefer constructor injection, it will make your code much easier to maintain and test. E.g., could your code be transformed into:
[Export(typeof(IModule))]
public class ExplorerModule : IModule
{
[ImportingConstructor]
public ExplorerModule(IPersistenceGateway gateway)
{
}
}

Resources