PDA

View Full Version : (java) Proper way to set up a program with objects




bigMAC28
Apr 17, 2012, 09:07 PM
I am wondering what the proper conventions are for setting up a java programming with objects. Keep in mind i learned about objects last lecture and i don't know everything about them yet. I know about mutator methods, accessor methods ,instantiation, and constructor. I guess I'm asking what order from top to bottom they should be in?



lee1210
Apr 17, 2012, 09:40 PM
Unfortunately your phrasing doesn't really tell us what you know and what you need to know. Java is object-oriented, period. The entry point to your program is a particular method (static public void main(String [])) on an object. You can try to twist it into an iterative language by never declaring another object, only using static methods, and putting all of your logic into main, etc. But this is going against the grain.

Dependent on the kind of program you're writing main should be a few lines that instantiate an object (using a constructor) and accessing its methods. The real thrust of OOP is encapsulation and reusability. Mutators and accessors break encapsulation a bit, but they are still frequently needed and used. I'm not sure what top to bottom sort of description you're wanting otherwise. Objects are a representation of a set of variables (data) and methods that act on them. There are a lot of additional complexities and abstractions like inheritance (one class inherits data and methods from another class), interfaces (a set of methods a class must adhere to in order to implement the interface), and many others.

Have you programmed in iterative languages before and this is your first OOP experience, or is this your first foray into programming of any variety?

-Lee

macsmurf
Apr 18, 2012, 02:48 AM
Not sure if this is what you're asking but this is the general layout of a simple class:


public class FooBar {

// Fields
private Object foo;
private Object bar;

// Constructors
public FooBar() {
}

public FooBar(Object foo) {
this.foo = foo;
}

// I normally put methods that are not standard getters/setters
// here because I think the most important part of the class in
// terms of functionality should be near the top.
// That implies putting private methods here as well.
// Most people put public methods at the top and private methods
// at the bottom, though.

// Standard getters/setters
public Object getFoo() {
return foo;
}

public void setFoo(Object foo) {
this.foo = foo;
}

public Object getBar() {
return bar;
}

public void setBar(Object bar) {
this.bar = bar;
}
}