Link to home
Start Free TrialLog in
Avatar of yeskarthikeyan
yeskarthikeyan

asked on

Structure in Java

Hi,

     can i create a structure progrmming in java like C++ structure.
Avatar of zzynx
zzynx
Flag of Belgium image

In java everything is a class
ASKER CERTIFIED SOLUTION
Avatar of zzynx
zzynx
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yes, Java is fully support Object Oriented Programming.

look at the zzynx codes, and you should be obvious on the structure in java programming.
Then you can

MyData data = new MyData();
data.setMyInt(10);
data.setMyBool(false);
data.setMyLong(12300);

List listOfData = new ArrayList();
listOfData.add(data);

MyData data2 = new MyData();
data2.setMyInt(15);
data2.setMyBool(true);
data2.setMyLong(3400);
listOfData.add(data2);
public class MyStructure
{
   public int myInt;
   public boolean myBool;
   public long myLong;
}


MyStructure x = new MyStructure();
x.myInt = 6;
x.myBool = true;
x.myLong = x.myInt * 100;


C++ is the same way as Java.  A struct is just a class with the default access as public instead of private:
struct myStruct
{
  int int;
  BOOL myBool;
  long myLong
}
is the same as
class myStruct
public:
  int int;
  BOOL myBool;
  long myLong;
}

In fact you can even put methods in a struct in C++.

As for Java, in OOP it is generally not recommended to create classes that have public fields.  This is because the fields are your implementation of the object and it gets difficult to maintain and/or change your class when all of the access is through the public fields.  One exception to this rule is simple classes.

For example, you could imlement a point like this:
class Point
{
   int x,y
   public Point(int x, int y)
   {
      this.x=x;
      this.y=y;
   }
}
Since it is a smple class and probably won't change and have methods on it, there is no need to make getter/setters for it.

Then for more complex classes they can use Point directly and gain a few milliseconds improvement in speed.

Class Line
{
   private Point start, end;
   public Line(int x1, int y1, int x2, y2)
   {
       start=new Point(x1, y1)
       end=new Point(x2, y2);
   }

   public Point getStart()
   {
      return start;
   }
   public Point getEnd()
   {
      return end;
   }
   public int getLength()
   {
       return ...//Code to compute length of line
    }
}
Thanks for accepting.
Can you explain me why the answer only deserves a C-grade?