Add object class java

How to add an object into another Object set

I have two classes. One(Person) for getters and setters, and another(People) for compute the data. What is my situation is, I get the data from the DB using ResultSet , then created a person Object to store the row data. Then i created people Object to store all persons. Each Object created as SET.

while(rs.next()) < Setpeople = new HashSet(); Person person = new Person(); String name = rs.getString(2); person.setName(name); int person.setId(id); String dept = rs.getString(4); person.setDept(dept); int age = rs.getInt(3); person.setAge(age); people.add(person); > return people; 

6 Answers 6

My understandig from your design is that you have a People has-many Person relation, so the People class holds a collection of Person objects. Then I’d expect something like this:

public class Person < private String name; private Date dateOfBirth; // .. more attributes // getters and setters // overrides of equals, hashcode and toString >public class People implements Set  < private Setpersons = new HashSet(); public boolean add(Person person) < return persons.add(person); >// more methods for remove, contains, . > 

So in your database related code you wouldn’t need to create another set, because People already has the one you need:

People people = new People(); // or get it, if it's already created while(rs.next()) < Person person = new Person(); String name = rs.getString(2); person.setName(name); int person.setId(id); String dept = rs.getString(4); person.setDept(dept); int age = rs.getInt(3); person.setAge(age); people.add(person); >return people; 

I don’t understand why you would want 2 classes in the first place. You cand have Person implement the computational part as well. But, nevertheless, what you could do:

class People implements Set  < private HashSethashset = new HashSet(); // . your computational code goes here // delegate all Set methods to hashset > 
People people = new People(); while(rs.next()) < Person person = new Person(); String name = rs.getString(2); person.setName(name); int person.setId(id); String dept = rs.getString(4); person.setDept(dept); int age = rs.getInt(3); person.setAge(age); people.add(person); >return people; 

I understand Person is a data structure (bean-like, with getters and setters), and People should contain all Person objects from the database and perform calculations on them.

If that is true, first of all, you cannot declare people within the loop (because a new People object will be created for each Person , and you don’t want that, from what I understand).

Second, People needs to be able to contain Person objects. So it should at least be composed of a Set of Person objects. You can add more functionality as you please. So, try something like this:

public class People < Setpersons = new HashSet(); Set getPersons() < return persons; >int computeSomethingAboutPeople() < // return as you please >> 

And use it like this, as the previous poster suggested:

People people = new People(); while(rs.next()) < Person person = new Person(); String name = rs.getString(2); person.setName(name); int person.setId(id); String dept = rs.getString(4); person.setDept(dept); int age = rs.getInt(3); person.setAge(age); people.getPersons().add(person); >int answer = people.computeSomethingAboutPeople(); 

Источник

An add method to add objects in your custom java class

A simple question on Java class I want to create my class with my own add method which adds an object of a different class. For eg if my class name is Weapon, I want to create an add method like void add(Gun gun) (Gun being one of my other classes for example) This would be just like creating your own collection maybe. if I am not wrong? Like list.add() method, I want to implement my own add method for the Weapon class So when I instantiate an object of my weapon class, it should be like Weapon w = new Weapon(new Gun( . .. constructor parameters) ) Also I would like to have variants of my add methods. Like a different add method with different parameters like void add(Weapon weapon) ( creating an method to add your own class object ) So I am not sure if this is similar to implementing a collection?? And if it is how do I achieve it? Do I have to extend another class for this? Apologies if my question confused anyone! 🙂

Читайте также:  Simplexml php as array

You are right, it does confuse me. It is unclear what you are trying to achieve and what your actual problem is. If you want an add() method, what stops you from writing one? What does it has to do with collections?

Just to point out the obvious: Weapon w = new Weapon(new Gun(. )) doesn’t really make sense to me. On the other hand, Weapon w = new Gun(. ) does.

Personally, no, it’s not, technically Collection , unless all the objects you are trying to add are based from a common parent, then it might be, but considering you are trying to provide functionality different objects types, I’d personally avoid it. Instead, I would use a List internally for each type of object you want to included, assuming you can have more than one.

If the desired behavior of Weapon ist not only similar to, but actually the same as the behavior of Collections (as I understood), why do you want to reimplement it? Just reuse the classes the Java API offer. Extending is an option, but also just adding a collection as a class member is easy to implement.

Источник

Adding Objects to JFrame from another class?

I’m trying to create a blackjack program for my final project in Java. I’m still very new to Java and OOD so I apologize if my problem seems very trivial to you 🙁 How my program works: I have three classes so far. main.java This class builds my frame and runs all the other methods. cards.java This class creates an array that holds the card values and location to picture. I have a for loop in there that auto-populates it. hits.java This class is meant to «randomly» generate a number that will represent the chosen card. The way this works is by taking the randomly created int and pointing it to a matching index location on the array. I assign the value to string objects that I then try to add to a jlabel and then add that jlabel to my main frame. The code is as follows: hits.java

// Import necessary classes. import java.util.Random; public class hits < // Create random object. Random rand = new Random(); // Declare variables. int card; String cardVal, cardPic; // Instantiate the needed classes. main s = new main(); cards t = new cards(); // Constructor for the class. public hits() < // Randomly generate a number (0 - 9). card = rand.nextInt(10); // Populate the array. t.runCards(); // Assign the cards according to the num. generated. cardVal = t.deck[card][0]; cardPic = t.deck[card][1]; >// Run Method public void runHits() < // Add the card chosen to the GUI. s.a.setText("hello"); s.dealerCards.add(s.a); >> 

I have «hello» as the text for the label because I wanted to see if perhaps my array was not populating, but even that doesn’t work. If it helps here is my main.java as well (constructor and main method):

// Constructor for the main class. public main() < // Setup the MAIN container. f1.getContentPane().setLayout(new GridLayout(0, 1)); f1.setSize(200, 200); f1.add(dealerName); f1.add(dealerCards); f1.add(userCards); f1.add(userName); // Setup the inner panels. dealerCards.setLayout(new GridLayout(1, 2)); dealerCards.add(b); userCards.setLayout(new GridLayout(1, 6)); userCards.add(c); userCards.add(d); >// Build the frame. public void GUILaunch() < // Display Frame f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f1.setVisible(true); >// Main method. public static void main(String args[]) < // Distribute the dealer's/player's starting hands. hits deal = new hits(); deal.runHits(); // Launch the GUI main gui = new main(); gui.GUILaunch(); >

Hopefully I have provided enough information to help you understand what’s going on here. So to sum it all up: how can i add my jlabel(from another class) holding the randomly selected card to my main frame Thanks in advance.

Читайте также:  Кнопка

Источник

Java: Adding fields and methods to existing Class?

Is there, in Java, a way to add some fields and methods to an existing class? What I want is that I have a class imported to my code, and I need to add some fields, derived from the existing fields, and their returning methods. Is there any way to do this?

I am not sure why people down-voted this. I think what the guy wanted is an equivalent to extension methods from C#, where you don’t have to subclass class A, but you can write an extension method foo() that then you can call on anything that is A or inherits from A. (A.foo()). Now I don’t know if there is such thing, but it is tremendously useful.

I am also looking for the functionality Daniel described above. I can’t subclass the existing class (Selenium’s Window class) because a lot of framework code instantiates it and I can’t update them to instantiate my subclass instead. So I need to inject few methods into this class. The alternative is to create a new class hierarchy, but injecting methods directly into Window class would be cleaner. Does Java have something similar to C# extension methods?

4 Answers 4

You can create a class that extends the one you wish to add functionality to:

public class sub extends Original

To access any of the private variables in the superclass, if there aren’t getter methods, you can change them from «private» to «protected» and be able to reference them normally.

The OP asked about adding to an existing class, so suggesting creating a new class obviously doesn’t satisfy the request.

Читайте также:  Mysqli stmt bind result php

You can extend classes in Java. For Example:

public class A < private String name; public A(String name)< this.name = name; >public String getName() < return this.name; >public void setName(String name) < this.name = name; >> public class B extends A < private String title; public B(String name, String title)< super(name); //calls the constructor in the parent class to initialize the name this.title= title; >public String getTitle() < return this.title; >public void setTitle(String title) < this.title= title; >> 

Now instances of B can access the public fields in A :

B b = new B("Test"); String name = b.getName(); String title = b.getTitle(); 

Edit: If class A has a constructor like:

public A (String name, String name2)
public B(String name, String name2, String title) < super(name, name2); //calls the constructor in the A this.title= title; >

Thanx, rather helpful! now how many super(field) i can use, because if the constructor of ex. the upper paradigms has two fields the second is getting wrong.

Ah, you just do one call to super. Basically it is calling the constructor of the parent class. So you only call it once in the constructor and it must be the first line. See edit.

The examples only really apply if the class you’re extending isn’t final. For example, you cannot extend java.lang.String using this method. There are however other ways, such as using byte code injection using CGLIB, ASM or AOP.

Assuming this question is asking about the equivalent of C# extension methods or JavaScript prototypes then technically it is possible as this one thing that Groovy does a lot. Groovy compiles Java and can extend any Java class, even final ones. Groovy has metaClass to add properties and methods (prototypes) such as:

// Define new extension method String.metaClass.goForIt = < return "hello $" > // Call it on a String "Paul".goForIt() // returns "hello Paul" // Create new property String.metaClass.num = 123 // Use it - clever even on constants "Paul".num // returns 123 "Paul".num = 999 // sets to 999 "fred".num // returns 123 

I could explain how to do the same way as Groovy does, but maybe that would be too much for the poster. If they like, I can research and explain.

Источник

Оцените статью