Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: OOP and java

  1. #1
    Junior Member
    Join Date
    Dec 2012
    Location
    Texas
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question OOP and java

    I am a bit new to java and had decided to program for my nexus7... I am well versed in C++ and was wondering if it was possible to structure code similarly to what you would see in a C++ project in java. The way I see projects in my mind are lots of little classes that each do their own thing to make the whole program work.

    C++ you would make a header and a code file for each class header gets a brief over view of the public and private members of the class and prototypes of all the functions/constructors/destructors.

    From what I have seen - so far - java is a run on coding spree with the only structure being the braces. Is it possible to make classes in their own .java files and to make them easily portable?

    I am currently writing code to access the accelerometer on my tablet:

    My overall intention of this class is to give a single function that will setup the accelerometer and do error checking giving us feedback if everything went well. Then there will be 3 floating point functions that will return X,Y,Z with values between -1 and 1.

    package com.example.breakout;
     
    import android.app.Activity;
    import android.content.Context;
    import android.hardware.Sensor;
    import android.hardware.SensorEvent;
    import android.hardware.SensorEventListener;
    import android.hardware.SensorManager;
     
    public class UpdateAccel extends Activity implements SensorEventListener
    {
    	private boolean ENABLED = false;
    	private Sensor accel;
            private float aX, aY, aZ;
     
    	public boolean init()
    	{
    	   SensorManager sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    	   if(sm.getSensorList(Sensor.TYPE_ACCELEROMETER).size() == 0)
    	   {
    		   ENABLED = false;   //no accelerometer installed!
     
    	   }else
    	   {
    		   ENABLED = true;    //accelerometer is installed!
    		   accel = sm.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
    		   if(!sm.registerListener(this, accel,SensorManager.SENSOR_DELAY_GAME))
    		   {
    			   ENABLED = false;
    			   //something went wrong during registering.
    		   }
    	   }
     
    	   return ENABLED;   
    	}
            public float getXvalue()
            {
                return aX;
            }
            public float getYvalue()
            {
                return aY;
            }
            public float getZvalue()
            {
                return aZ;
            }
        @Override
    	public void onAccuracyChanged(Sensor arg0, int arg1) 
    	{
    		// TODO Auto-generated method stub
     
    	}
     
    	@Override
    	public void onSensorChanged(SensorEvent arg0) 
    	{
    		aX = arg0.values[0];
                    aY = arg0.values[1];
                    aZ = arg0.values[2];
                    //normalize to -1 to 1
    		aX = aX/9.8;
                    aY = aY/9.8;
                    aZ = aZ/9.8;
                    //not always 100 percent accurate do some rounding to keep within limits
                    if(aX > 1)aX = 1;
                    if(aX < -1)aX = -1;
                    if(aY > 1)aY = 1;
                    if(aY < -1)aY = -1;
                    if(aZ > 1)aZ = 1;
                    if(aZ < -1)aZ = -1;
    	}
    }

    My Ideal implementation would be similar to:

    package com.example.breakout;
     
     
     
    import android.content.Context;
    import android.graphics.BitmapFactory;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.view.SurfaceHolder;
    import android.view.SurfaceView;
     
     
    public class GameView extends SurfaceView implements SurfaceHolder.Callback 
    {
            private SpriteObject[] Bricks = new SpriteObject[10];
    	private SpriteObject Ball;
    	private SpriteObject Paddle;
    	private GameLogic mGameLogic;
            private UpdateAccel myAccel;
     
    	public GameView(Context context) 
    	{
    		super(context);
    		getHolder().addCallback(this);
     
    		for(int i = 0; i < 10; i++)
    		{
    			Bricks[i] = new SpriteObject(BitmapFactory.decodeResource(getResources(), R.drawable.redbrick), 10+i*20, 50);
    		}
    		Ball = new SpriteObject(BitmapFactory.decodeResource(getResources(), R.drawable.ball), 100, 100);
    		Ball.setMoveY(1);
    		Ball.setMoveX(1);
    		Paddle = new SpriteObject(BitmapFactory.decodeResource(getResources(), R.drawable.paddle), getWidth()/2, getHeight()/2);
     
    		mGameLogic = new GameLogic(getHolder(), this);
                    if(!myAccel.init())
                    {
                        mGameLogic.RUNNING = false;
                    }
     
    		setFocusable(true);
    	}
     
    	@Override
    	public void surfaceChanged(SurfaceHolder holder, int format, int width,
    			int height) {
    	}
     
    	@SuppressWarnings("static-access")
    	@Override
    	public void surfaceCreated(SurfaceHolder holder) {
    		mGameLogic.setGameState(mGameLogic.RUNNING);
    		mGameLogic.start();
    	}
     
    	@Override
    	public void surfaceDestroyed(SurfaceHolder holder) {
    	}
     
     
     
    	public void onDraw(Canvas canvas) 
    	{
    		canvas.drawColor(Color.BLACK);
    		for(int i = 0;i < 10;i++)
    		{
    			if(Bricks[i] != null)
    			{
    				Bricks[i].draw(canvas);
    			}
    		}
    		Paddle.draw(canvas);
    		Ball.draw(canvas);
    	}
     
    	public void update(int adj_mov) 
    	{
    		//handles when ball hits side of the screen
    		if(Ball.getX() <= 5 && Ball.getMoveX() < 0)Ball.setMoveX(Ball.getMoveX() * -1);
    		if(Ball.getX() >= getWidth() - 5 && Ball.getMoveX() > 0)Ball.setMoveX(Ball.getMoveX() * -1);
    		if(Ball.getY() <= 5 && Ball.getMoveY() < 0)Ball.setMoveY(Ball.getMoveY() * -1);
    		//done with screen
     
    		//for testing bounces.
    		if(Ball.getY() >= getHeight() - 5 && Ball.getMoveY() > 0)Ball.setMoveY(Ball.getMoveY()*-1);
    		//end testing
     
    		Ball.update(adj_mov);
     
    		if(Paddle.getX() == 0 && Paddle.getY() == 0)
    		{
    			Paddle.setX(getWidth()/2);
    			Paddle.setY(getHeight()-15);
    		}
     
     
                    Paddle.setX((getWidth() / 2) + ((getWidth()-30) / 2) *myAccel.getXvalue());   //bitmap is 30 units wide this would keep us from falling off the screen.
     
     
    	}
     
     
    }


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: OOP and java

    From what I have seen - so far - java is a run on coding spree with the only structure being the braces. Is it possible to make classes in their own .java files and to make them easily portable?
    I am not sure what you have seen, but java is far from this - it is completely object oriented. Code written by beginners often neglect object oriented programming, and may seem more like procedural/scripting - if you look at some common production libraries or more advanced code (for instance Swing or Collections libraries that are part of J2SE) you will see some good examples.

    Just glancing at your second code snippet, as I understand it this single class seems responsible for drawing and logic - in many scenarios a situation in which both should be separated into individual interface/classes (if you are familiar with the Model-View-Controller concept, this is what I am referring to)

  3. #3
    Junior Member
    Join Date
    Dec 2012
    Location
    Texas
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: OOP and java

    Quote Originally Posted by copeg View Post
    Just glancing at your second code snippet, as I understand it this single class seems responsible for drawing and logic - in many scenarios a situation in which both should be separated into individual interface/classes (if you are familiar with the Model-View-Controller concept, this is what I am referring to)
    They should be, so far all my examples have shown it done this way. In general my logic is usually separated. In the cases I have seen java has been some thrown together stuff. No doubt minecraft isn't thrown together like that - but I haven't seen a very good example so far on android. In my mind each input should have a handler class and since I want to use the accelerometer to move the paddle I want it to have it's own class. Sprites have their own class, but really, a brick and a ball are two different objects in my mind. I haven't seen any swing examples for android(yet), but that doesn't mean it doesn't work. So far I have seen a main class with other classes shoved in it. This makes no sense to me since when I write in C++ I usually manage to write a class for everything and container classes to make it easier to work with. I have seen interfaces used they look similar to a header file - ie no real code. Where does the code come in?

  4. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: OOP and java

    Quote Originally Posted by ~Kyo~ View Post
    They should be, so far all my examples have shown it done this way. In general my logic is usually separated.
    In the second code snippet above, there are two methods: onDraw and update. The former seems to draw, the latter move things. My point was that the former seems to deal with the view, the latter with the model, yet they are not separated (at least at the class level). If you are not familiar with the MVC concept it is complicated but very powerful, and worth studying. Again, I may be misunderstanding the code as it is not in full and I am a bit unfamiliar with the Android API.

    Quote Originally Posted by ~Kyo~ View Post
    In my mind each input should have a handler class and since I want to use the accelerometer to move the paddle I want it to have it's own class. Sprites have their own class, but really, a brick and a ball are two different objects in my mind. I haven't seen any swing examples for android(yet), but that doesn't mean it doesn't work.
    If you are used to separating things into in a particular manner, I am not sure what exactly is stopping you. Do what works, what makes sense, and what makes things maintainable. You will probably look back months later wondering what the heck you were thinking (I am guilty of this I must admit) - so comments help immensely. Again I am not sure what examples you are looking at, but keep in mind many examples found in tutorials are intentionally small to maintain focus on the point of the exercise.

    Quote Originally Posted by ~Kyo~ View Post
    I have seen interfaces used they look similar to a header file - ie no real code. Where does the code come in?
    See What Is an Interface? (The Java™ Tutorials > Learning the Java Language > Object-Oriented Programming Concepts)

  5. #5
    Junior Member
    Join Date
    Dec 2012
    Location
    Texas
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: OOP and java

    Quote Originally Posted by copeg View Post
    In the second code snippet above, there are two methods: onDraw and update. The former seems to draw, the latter move things. My point was that the former seems to deal with the view, the latter with the model, yet they are not separated (at least at the class level). If you are not familiar with the MVC concept it is complicated but very powerful, and worth studying. Again, I may be misunderstanding the code as it is not in full and I am a bit unfamiliar with the Android API.

    See What Is an Interface? (The Java™ Tutorials > Learning the Java Language > Object-Oriented Programming Concepts)
    They have some strange deals in android so it is likely android related. I am in the process of breaking it into smaller parts - unfortunately lets take the accelerometer and the specific question in the other forum(http://www.javaprogrammingforums.com...-crashing.html). I can't even get the code to run properly without crashing on the tablet. I took code from an example - named it something that tells me it is just updating the accelerometer(hence the name). I would gladly separate the draw and the logic, but for now it is getting things to work and play around seeing what I can do with the code. I will read the interface page tonight when I go to lunch at work. Right now if I am working backwards which is probably a pretty bad thing to do and would normally be better off writing from scratch.

  6. #6
    Junior Member
    Join Date
    Dec 2012
    Location
    Texas
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: OOP and java

    Ok so in short interfaces are promises to make any class that implements them to have specific functions. So in a way it is like having inheritance with promises of overloading any functions from the parent class. A bit odd, but I guess I can go with that. Kind of wish java had a vector class like STL does in C++ closest thing I found is this ArrayList deal.

    As far as separate logic I think they just split it in different functions since they were focusing on a small problem and not something large(r). I am going to try and just do some basic textout stuff with the accelerometer to play around first I suppose. Thanks for the insight - I will just keep reading up in my book java doesn't seem too far off from C++.

  7. #7
    Junior Member
    Join Date
    Jan 2013
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: OOP and java

    If you not get proper solution search on google and get the solution of your problem.

Similar Threads

  1. Is Java 100% OOP
    By kbbaloch in forum Object Oriented Programming
    Replies: 5
    Last Post: December 29th, 2011, 12:54 AM
  2. OOP help!
    By imaznumkay in forum Object Oriented Programming
    Replies: 3
    Last Post: July 11th, 2011, 01:43 PM
  3. Free Application or Software for Java Programming focused on OOP
    By seicair in forum Java Theory & Questions
    Replies: 3
    Last Post: June 14th, 2011, 01:00 AM
  4. [SOLVED] OOP java assignment
    By enkei in forum Object Oriented Programming
    Replies: 1
    Last Post: April 27th, 2011, 11:16 AM
  5. Need Ideas For OOP(Java) Mini Project
    By rizwansheikh in forum Object Oriented Programming
    Replies: 6
    Last Post: December 13th, 2010, 01:47 PM