How can I implement C's Structs in Java? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a little code that let me register an student (ID, name, age, etc), right now I could do it but just accepting one user, would overwrite if I register a new one, which is what I need now, be able to have more than 1 student.
So I was thinking that if I were using C I would use structs, something like this
struct Students {
int ID[6];
char Name[35];
char Age[2];
} student;
After reading a bit, Java doesn't have this facility.
How to do this in Java ? Is it possible ?
Thanks

Java has no struct.
You can use class as structs with members having public access specifier and no methods

In Java you could make a class for students. Once you get to know java better you should change those properties to either private or protected and use public getter/setter methods.
public class Student{
public int id;
public String name;
public int age;
}
And then in your main code you could create however many students you need:
Student myStudentA = new Student();

It is true that in C you would use structs to embody the information you need for each student.
In object-oriented languages like Java, you would use classes. So the equivalent to the C structure you defined would be something like the following class in Java:
public class Student
{
public int id; // [*]
public String name;
public String age;
//... other things go here, such as constructors and methods ...
}
[*] You defined the id member to be an array of 6 integers. I assume that you probably meant it to be a single integer value that could hold up to 6 digits.
You probably also want to define the age member to be a integer instead of a two-character string.
Note that in Java, String variables do not have a maximum length like null-terminated C character arrays do.

It is absolutely possible to do this in Java. Java is an object oriented programming language so when you are dealing with "things", such as students, it is very easy to implement them into a Java class.
Here is one of many ways you could do this:
public class Students{
private List<Student> students;
public Students(){
this.students = new ArrayList<>();
}
public void addStudent(Student newStudent){
students.add(newStudent);
}
public Student getStudents(){
return this.students;
}
public Student getStudent(int name){
for(Student s : students){
if(s.getName().equalsIgnoreCase(name)){
return student();
}
}
return null;
}
public class Student{
private int id;
private String name;
private int age;
public Student(){
}
public Student(int id, String name, int age){
this.id = id;
this.name = name;
this.age = age;
}
// Getters and Setters for the Students variables
}
}

Related

Best approach for designing a Java class? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I hope I am asking the right question. This is just out of my curiosity and since I am not an experienced developer, I just to wanted to hear from you guys that what is the good approach while designing a class. Is there any standard approach or either one can be implemented? I just to want to know what is the conventional way of creating a class or what is your way?
Option 1:
public class Student{
private String name;
private String address;
public Student(String name, String address){
this.name = name;
this.address = address;
}
public void addStudent(){
//add name and address to database.
}
}
Option 2:
public class Student{
public void addStudent(String name, String address){
//add name and address to database.
}
public void addAllStudent(List Student){
//loop and add each student to database
}
}
Method call:
//option 1:
Student s = new Student("abc","xyz");
s.addStudent();
//for list,
for(int i=0;i<list.length;i++){
Student s = new Student(list[i].name, list[i].address);
s.addStudent();
}
//option 2:
Student s = new Student();
s.addStudent("abc","xyz");
s.addAllStudent(list);
Option 2 is not good, since both methods dont really have anything to do with the Student object they belong to. You could make those two methods static. Option 1 is the "right" way for a Student class, but the method addStudent() is wrong. You can have a method in your database and call database.addStudent(objStudent).
You could also change the addStudent method in your Student class to addToDatabase(Database db) or even
static void addToDatabase(Student student, Database db)
In the specific case of a List as Database, there is no need for a custom add method at all, because List allready has the add method.
In the most simple case it all boils down to:
List<Student> students = new ArrayList<Student>();
students.add(new Student("Max", "###"));
If you think the second line is too complicated, you can create a static method in Student:
public static void addStudent(String name, String address, List<Student> students)
{
students.add(new Student(name, address);
}
Then you can use it like this:
List<Student> students = new ArrayList<Student>();
Student.addStudent("Max", "###", students);
From personal preference i would not do the latter. It bugs me a little that its not transparent enough in terms of what the method actually does with the list. There is nothing wrong with simply using the add method of the list in the first case.
As you can see there are a lot of opinions on this question, so I go and add another one ;)
Someone commented that there is no "silver bullet" to use when creating new instances of a class. That pretty much hits the bull's eye. There are many ways, straight forward via a constructor, via static methods or wrapped in Factories. And there are even very good arguments to create an instance via reflections.
The same is true for how to save your students to the database. There are many patterns that may be valid. Just make sure you understand how that pattern works and what are the benefits and disadvantages. And just as important, use it consequently throughout your code.
Regarding your code, your option 2 does not make sense if you change to a modeling perspective. Adding students to a student? Unless you don't want to create a human pile of students, you better add students to a course, a class, a school...
Well... first things first... there is a difference between the a Studentand a List<Student>
Normally you would create a class Student
public class Student{
private String name;
private String address;
public Student(String name, String address){
this.name = name;
this.address = address;
}
// and some getter
}
and somewhere else in your code you can use a java List (not in your Student-Class)
List<Student> students = new ArrayList<Student>();
Student peter = new Student("Peter", "somewhere");
Student frank = new Student("Frank", "somewhere else");
students.add(peter);
students.add(frank);
This Code snipped could be in your SubscribeStudentToCourseService or so...
What you want to do is - SingleResponsibility:
Create a class which is responsible for only one thing:
a StudentClass which represents the student as a java model
a course which represents a course (perhaps with a List<Student> field for the students who visit the course
perhaps you write a Service To subscribe Students to a course
It seems you are using the same class to provide a template for a Student, and also to store Students.
Do you really need to store students in the same class? It will lead to some confusing design, where you've got a Student class storing other Student classes which actually represent a student.
Perhaps the functionality for adding a student could be in a separate class, such as a School? Or you just create a generic List of Students wherever you need them. So the addStudent functions could possibly be removed from the class and stored elsewhere.
You can try something like this:
Create a Student bean
public class Student {
private String name;
private String address;
public Student(String name, String address) {
this.name = name;
this.address = address;
}
// generate the getters and setters
}
Create the DAO class
public class StudentDaoIml {
public void addStudent(Student student) {
// do the add student job here
}
public void addAll(List<Student> students) {
// the code goes here
}
public void deleteStudent(Student student) {
}
...
}
At the end you can use it like this:
StudentDaoIml stDao = new StudentDaoIml();
for(int i=0;i<someValue; i++){
Student s = new Student(list[i].name, list[i].address);
stDao.addStudent(s);
}
Here's a good way and some explanation in comments.
public class Student{
private String name;
private String address;
public Student(String name, String address){
this.name = name;
this.address = address;
}
public void save(){
//save this instance to database.
}
public static void saveAll(List<Student> students){
//Either iterate and call save
// or do better batch insert for better performance
}
}
As far as naming a method is concerned, class methods are named in terms of their behaviour. Think of it like telling an instance of student to 'go and save yourself to DB'. There could be one more method like 'go and update yourself in DB'.
When you are dealing with a list, the list itself should not be part of the Student class. Keep the list somewhere else. However, the Student class could have a static method which takes a list of students and saves them in one shot.
For example, the students could be in a class in a school. Then
Student.saveAll(class5A.getStudents());
Create a few and save them:
List<Student> students = new ArrayList<>();
for(int i=0;i<10;i++){
Student s = new Student("Student" + i, "Student address " + i);
students.add(s);
}
Student.saveAll(students);
Going one step further, Student class should probably not deal with saving students in bulk. So, let's relieve it of that duty and let the BatchOfClass take care of that.
public class Student{
private String name;
private String address;
public Student(String name, String address){
this.name = name;
this.address = address;
}
public void save(){
//save this instance to database.
}
}
public class BatchOfClass{ //Students who are in grade 6 in 2016
private String className;
private String batchName;
private List<Student> students;
public BatchOfClass(...){
}
public void save(boolean saveStudents){
//save this instance to database.
//This would also save the students to DB if saveStudents==true
}
}

how to pass an object to another object in java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to java in general but I am having a lot of trouble with objects specifically. I have a project to pass an object to another object. I've looked all over the internet for help, my online java textbook doesn't explain objects in detail. So my question is, how would you pass an object to another object.
-Thank you in advance
Messaging between objects is a core concept in object-oriented programming. To "pass an object to another object" generally just means that one object exposes a method which accepts the type of another object as a parameter to that method. It could be something as simple as this:
class Person {
private String name;
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
}
class Car {
private Person driver;
public void setDriver(Person driver) {
this.driver = driver;
}
}
Then somewhere in the code, you'd have an instance of a Car and an instance of a Person, and you'd call that method:
carInstance.setDriver(personInstance);
Those instances could have been created lots of different ways. Perhaps even as simple as:
Person personInstance = new Person();
personInstance.setName("David");
Car carInstance = new Car();
You can pass an object o1 to another object o2 through calling a method of o2 (or a constructor of o2's class in particular; constructors as you know are special types of methods).
I suggest you start by figuring out what this code below does.
How many persons are there?
What are their names at different moments of the execution of the program?
How many times and where a Person object is passed to a Person object?
How many times and where a String object is passed to a Person object?
If you digest this, you'll be good for now.
class Person {
private String name;
public Person(String name){
this.name = name;
}
public Person(Person p){
this.name = p.name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class MainProg {
public static void main(String[] args) {
Person t1 = new Person("Joe");
Person t2 = new Person("John");
System.out.println(t1.getName());
System.out.println(t2.getName());
t1.setName("Mark");
System.out.println(t1.getName());
System.out.println(t2.getName());
Person t3 = new Person(t1);
System.out.println(t3.getName());
}
}

Constructor over methods in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to know the exact scenario of using constructor over methods can anyone give me the exact example program for constructors over methods in java
They are not similar things to compare even.
Both serves completely different purposes and even you have to note that constructor wont return anything, not even void :)
If you see a basic tutorial on Constructor, mentioned
Constructor declarations look like method declarations—except that they use the name of the class and have no return type.
So you cannot choose one over them.
If you are looking/talking about setting variables of instance memebers, choose setter methods instead of variables.
Another scenoriao is some objects never complete without providing some basic info. In that cases you have to create a constructor like it should be built when necessary info passed in constructor.
Consider the below scenorio, where to create an employee class, He must have an employee Id
public class Employee {
String empId;
public Employee(String empId) {
this.empId = empId;
}
// Methods
public static void main(String[] args) {
Employee a = new Employee("green");
}
Consider the below scenorio, where to create an empty employee class, later he can assign employee Id
public class Employee {
private String empId;
public Employee() {
}
// Methods
public void setEmpId(String empId) {
this.empId = empId;
}
public static void main(String[] args) {
Employee a = new Employee(); //No error
a.setEmpId("SOMEX007");
}
}

How to add an object in my collection by only using add method? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have to create a collection of Name,Address,Age.How do I create this as a collection object in java.
My snippet is as follows:
public class DataCollection implements java.io.Serializable{
private String Name;
private String Address;
private int Age;
}
And I have the getter and setter methods...
In the main method, how do I create this as a collection??
list.add(new DataCollection(??????) );
Can someone please help me on this?
public class DataCollection implements java.io.Serializable{
private String Name;
private String Address;
private int Age;
public DataCollection(String name, String address, int age){
this.Name=name;
this.Address=address;
this.Age=age;
}
}
After that create DataCollection objects:
DataCollection d1 = new DataCollection("nik", "10/5 cross", 20);//creation of List collection
Now put the object inside a collection:
List<DataCollection> list = new LinkedList<DataCollection>();
list.add(d1);
You can iterate like below:
List<DataCollection> list=new LinkedList<DataCollection>();
for(DataCollection d : list){
System.out.println(d);
}
It is not clear from your question exactly what you are asking. I suspect the problem is that you are trying to allocate a List, which is an abstract class. You should be allocating a LinkedList or an ArrayList, or something of that sort. For a minimal example:
import java.util.List;
import java.util.ArrayList;
public class DataCollection implements java.io.Serializable{
private String Name;
private String Address;
private int Age;
public static void main(String[] args){
ArrayList<DataCollection> list = new ArrayList<DataCollection>();
list.add(new DataCollection());
}
}
Then you can use list.get(index) to access the item in the list and set a name. The other problem may be that you want to pass arguments in when you create the object (such as the name, address, and age. If that is what you want to do, you need to look up overloading constructors.

Java Public Var question [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Property and Encapsulation
NEWB Alert!!
I am starting with Android and Java and I am starting to understand it but I am wondering why I should use getters and setters and not just public variables?
I see many people make a private variable and create a get and set method.
What is the idea here?
Its called encapsulation and the concept is central to object oriented programming. The idea is that you hide the implementation of your class and expose only the contract i.e. hide the how and only expose the what. You hide the variables by making them private and provide public setters-getters and other public methods which the clients invoke to communicate with your class. They are not tied to the actual implementation of the methods or how you store your variables.
For example, suppose you had this class where you stored a phone number as a Long object:
public class ContactInfo {
private Long phoneNo;
public Long getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(Long phoneNo) {
this.phoneNo = phoneNo;
}
}
Since the clients of the class only see the getter/setter, you can easily change the implementation of the class/methods by switching the phone number representation to a PhoneNumber object. Clients of ContactInfo wouldn't get affected at all:
public class ContactInfo {
private PhoneNumber phoneNo;
public Long getPhoneNo() {
return phoneNo.getNumber();
}
public void setPhoneNo(Long phoneNo) {
this.phoneNo = new PhoneNumber(phoneNo);
}
}
public class PhoneNumber {
private Long number;
public PhoneNumber(Long number) {
this.number = number;
}
public Long getNumber() {
return number;
}
}
The OOP concept involved is encapsulation (google it).
Some of the advantages are: you can specify different access level for setters (mutators) and getters (accessors), for example public getter and private setter. Another advantage is that you can add another code other than changing or retrieving the value. For example, you may want to check the validity of the set value, or you want to throw exceptions or raise some events in response to changing the variable to certain value. If you implement these inside an accessor or mutators, you can also change their implementations without changing any code outside of the class.
I believe the idea is "information hiding" http://en.wikipedia.org/wiki/Information_hiding
It also serves to control the access to variables (provides an interface). For example, you can provide a getter but not a setter, so that they may be read but not written. Whereas if everything was public any thing could read and write to the variables.
Also important is any checking/validation need to set a variable. For example you have a String name that is not allowed to be empty but if it is public it could easily be forgotten and set as name = "". If you have a setter such as public boolean setName(String newName) you can check newNames length and return true or false if it passes and is set or not
The concept is called encapsulation.
What it attempts to do is to separate the inner structure of a class from its behaviour.
For example, suppose a class like this
public class Point{
private float x;
private float y;
public float getX(){
return x;
}
public float getY(){
return y;
}
public float distanceToZero2(){
return x*x + y*y
}
public float getAngle(){
//havent considered the x = 0 case.
return atan(y/x);
}
public boolean isInFirstQuad(){
return x>0 && y>0;
}
}
In this case, encapsulation hides the inner structure of the class, and exposes only the operations available to a Point. If you dont like it, you can change its inner structure and mantain its behaviour (for example, changing carthesian coordinates to polar coordinates).
Anyoune who uses this class wont care about it, he /she will be happy that they have a Point class with this functionality.
Asides the encapsulation, you can also control the value get or set to your variable in some cases. For example, you want to validate the value of an age variable which should be >=1
class Person {
private int age = Integer.MIN_VALUE;
public void setAge(int age){
if(age>=1)
this.age = age;
}
public int getAge(){
return age;
}
}

Categories

Resources