Interacting classes in Java. How much interaction is possible? - java

I am new to java programming and know it is possible to have class as an attribute as another.
For instance you could have publisher as one class and strategyGame as another. Is there a way to have it so a method in publisher class that counts the amount of strategyGame objects there is, therefore ability to display the amount of strategy games that publisher has published?
Thank you

Here is a simple Snippet to keep you going..
Image you have StrategyGame class
public class StrategyGame {
private String name;
public StrategyGame(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And inside your Publisher class you keep a List of StrategyGame objects
public class Publisher {
List<StrategyGame> games;
public Publisher() {
games = new ArrayList<>();
}
public void publishGame(String name) {
games.add(new StrategyGame(name));
}
public int getHowManyGamesCreated() {
return games.size();
}
}
Now how to use it in your main?
public static void main(String[] args) {
Publisher publisher = new Publisher();
publisher.publishGame("Pacman");
publisher.publishGame("Asteroids");
System.out.println(publisher.getHowManyGamesCreated());
}

Related

How to merge two methods with the same implementation but different parameter types

The operations in my two methods are the same, but the input parameter types are different, so how can I optimize these two methods, it seems that they are not so repetitive?
Because their operations are the same, but the parameter types are different, what should I do to make this code more elegant?
public class Main {
public static void main(String[] args) {
BaseStudent baseStudent = new BaseStudent();
baseStudent.setName("base");
NbdStudent nbdStudent = new NbdStudent();
nbdStudent.setName("nbd");
updateName(baseStudent);
updateName(nbdStudent);
}
private static void updateName(BaseStudent student) {
student.setName("update base");
}
private static void updateName(NbdStudent student) {
student.setName("update base");
}
}
You should make your students class extend from the same (abstract) base class or implement the same interface.
Using classes
Since the two classes are both students you can define a common parent (lets say BaseStudent is the common parent)
/* BaseStudent.java */
// abstract is optional, depends on if you want
// to make the class instantiable or having some
// methods that are not implemented
abstract class BaseStudent {
public String name;
public void setName(String name) { this.name = name; }
}
/* NbdStudent.java */
class NbdStudent extends BaseStudent { }
/* main file */
public class Main {
public static void main(String[] args) {
BaseStudent baseStudent = new BaseStudent();
baseStudent.setName("base");
NbdStudent nbdStudent = new NbdStudent();
nbdStudent.setName("nbd");
updateName(baseStudent);
updateName(nbdStudent);
}
private static void updateName(BaseStudent student) {
student.setName("update base");
}
}
Using interfaces
In a more broad way you can abstract your classes to have a common behaviour but a different implementation
/* Named.java */
interface Named {
public void setName(String name);
}
/* BaseStudent.java */
class BaseStudent implements Named {
public String name;
public void setName(String name) {
// different implementation simple example
if (name == null) { name = "BaseStudent with no name"; }
this.name = name;
}
}
/* NbdStudent.java */
class NbdStudent implements Named {
public String name;
public void setName(String name) { this.name = name; }
}
/* main file */
public class Main {
public static void main(String[] args) {
BaseStudent baseStudent = new BaseStudent();
baseStudent.setName("base");
NbdStudent nbdStudent = new NbdStudent();
nbdStudent.setName("nbd");
updateName(baseStudent);
updateName(nbdStudent);
}
private static void updateName(Named student) {
student.setName("update base");
}
}

how to create a List type of non public class from another package?

My Package A has one java file with 2 classes. Login class which is public and LoginDetails class which cannot be public because it is in the same file. how to create a List of LoginDetails type from Package B.
package A;
public class Login {
private String name;
private String passWord;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
#Override
public String toString() {
return "Login [name=" + name + ", passWord=" + passWord + "]";
}
}
class LoginDetails{
public LoginDetails(int id, int geight) {
super();
this.id = id;
this.geight = geight;
}
private int id;
private int geight;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getGeight() {
return geight;
}
public void setGeight(int geight) {
this.geight = geight;
}
public void hidden() {
System.out.println("From hidden");
}
public LoginDetails() {
}
}
package B;
import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main(String[] args) throws Exception {
List<LoginDetails> l = new ArrayList<LoginDetails>();
}
}
A solution to your weird question which doesnt include changing neither of the Login nor LoginDetails classes would be by adding a second Public class called AUtils such like this:
AUtils/AFactory class
package A;
import java.util.ArrayList;
public class AUtils {
public static ArrayList<LoginDetails> generateList(){
return new ArrayList<LoginDetails>();
}
public static ArrayList<LoginDetails> generateListWithInitialSize(int x){
return new ArrayList<LoginDetails>(x);
}
public static LoginDetails generateAnObject(){
return new LoginDetails();
}
public static LoginDetails generateWithData(int id, int geight){
return new LoginDetails(id,geight);
}
}
And your Demo would look like this:
public class Demo {
public static void main(String[] args) {//plus you dont need To throw exception thus your program dont throw any!:)
List l = AUtils.generateList();
// List l = AUtils.generateListWithInitialSize(10);//will give you array list with initial size 10
l.add(AUtils.generateAnObject());//if you do so be aware that the objects would be created with 0 as id and eight.
// l.add(AUtils.generateWithData(3,3));
}
}
please be aware that this normally is not acceptable and considered as bad coding because its kinda turn around ;) so either you misunderstood the assignment or the one who wrote it is really a carrot.
happy coding.
You cannot do it directly without changing of the design or visibility of the classes.
If a class has no modifier (the default, also known as
package-private), it is visible only within its own package.
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

How do I minimize the amount of code for a hierarchy

This is for learning. I have an interface that is implemented by 2 classes, and I am supposed to reduce the amount of code I use in order to keep things more clean and less messy. Currently, the code looks like this:
public abstract class VClass implements IntFace {
protected String name;
public VClass(String name) {
this.name = name;
}
public int value (SClass sc) {//comes from a diff class
return sc.lookup(name);
}
public String getName() {
return name;
}
#Override
public String toString() {
return getName();
}
}
public abstract class NClass extends VClass implements IntFace {
public Number(String name) {
super(name);
this.name = name;
}
public int value (SClass sc) {
return sc.lookup(name);
}
public String getName() {
return name;
}
#Override
public String toString() {
return getName();
}
}
public interface IntFace {
public int value (SClass sc);
public String toString (int num);
}
can this code be more condensed?
You can remove the following things from your code:
implements IntFace from NClass declaration. Since NClass extends VClass, it implements IntFace as well.
this.name = name; from NClass constructor. name is initialized in a superclass constructor
value and getName methods from NClass. These methods are implemented in a superclass.
public modifier from interface methods declaration. Methods in interfaces are public by default.
Now you can also make name field private since it's no longer used in a NClass.

Java Encapsulation Constructor Method

Hi all I am working on a java code for student health. what I am trying do is
A) Make a constructor method that initializes only the first 2 data fields
(name and date-of-birth). Also, increment the patient counter data field.
B) Secondly make a constructor method that initializes all the data fields. Also, increment the patient counter data field.
If I recall correctly in order to make a constructor method that initializes the first two variables (in this case name and DOB) it goes something like this.
public emr (String name, Long dob){
However when I put that in my emr class my main method comes up with errors saying "constructor emr class cannot be applied to given types"
In my main Method I have
package studenthealthservices;
public class Studenthealthservices {
public static void main(String[] args) {
emr p1 = new emr();
p1.setName("Colin");
emr p2 = new emr();
p2.setName("Anquan");
emr p3 = new emr();
p3.setName("Buster");
emr p4 = new emr();
p4.setName("Hunter");
emr p5 = new emr();
p5.setName("Nori");
}
}
This is my emr class code
package studenthealthservices;
public class emr {
private String name;
private Long dob;
private String rfv;
private double bodyt;
private double hr;
private String diag;
private String pmeds;
public void setName(String name) {
this.name = name;
}
public Long getDob() {
return dob;
}
public void setDob(Long dob) {
this.dob = dob;
}
public String getRfv() {
return rfv;
}
public void setRfv(String rfv) {
this.rfv = rfv;
}
public double getBodyt() {
return bodyt;
}
public void setBodyt(double bodyt) {
this.bodyt = bodyt;
}
public double getHr() {
return hr;
}
public void setHr(double hr) {
this.hr = hr;
}
public String getDiag() {
return diag;
}
public void setDiag(String diag) {
this.diag = diag;
}
public String getPmeds() {
return pmeds;
}
public void setPmeds(String pmeds) {
this.pmeds = pmeds;
}
}
If you do not write a constructor, a public constructor with no arguments is created by default.
This default constructor is the constructor you are using in main when you write new emr().
However, when you write your own constructor, then the default constructor will not be created, so main will no longer compile. If you want main to continue to compile even after you have written the new constructor, you will have to also write a second constructor with no arguments.

How to pass an array of objects to a button?

I have two classes: one called Student and the other one called Course. I would like to make a simulation for a simple registration system.
My Student class part has the following form:
class Student
{
private String id,
private Course[] listOfCourses;
private int numCourse;
//accesing methods
public registration(Course course){
listOfCourses[numCourse]=course;
numCourse++;
}
public Course[] getCourse(){
return listOfCourses;
}
}
and the Course class has the following form:
class Course
{
String id, String courseName;
//constructor
//accesing methods
}
I would like that by pressing a buttom in a form made in Java Swing, to display the contents of the courses registered by one specific student into a jTable. I have tried the following, but with no results at all:
Student e=new Student();
Course d[]=new Course[4];
d=e.getCourses(); //to receive the array of Courses from the Student class
for (int i=0;i<d.length;i++){
jTable2.setValueAt(estLista[i].getName(), i, 0);
}
how I can do that? I mean there is a way in which I could get the contents of the array, that is stored in the Course class, into the ActionEvent of the button?
From the code you have provided I believe there atleast one reason why you are not getting the courses.. because it is not set in registration process:) (Also the syntax is not correct unless you have a registration class?) This might not be a complete solution but it corrects one of the problem
public void registration(Course course){
// listOfCourses[numCourse];
listOfCourses[numCourse]=course;
numCourse++;
}
Ok, it is not too clear for me yet, but I will put some code and tell me if it helps you.
Note: Not tested
For Student (sorry I prefer to use lists instead of arrays):
public class Student {
private String id;
private List<Course> takenCourses;
public void registration(Course course){
if (this.takenCourses != null) {
takenCourses.add(course);
} else {
System.err.println("an array has not been specified.");
}
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<Course> getTakenCourses() {
return takenCourses;
}
public void setTakenCourses(List<Course> takenCourses) {
this.takenCourses = takenCourses;
}
For course:
public class Course {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
For your UI, I just created a "simulation" of UI, I assume you have implemented something more complete... I assume you have intialized the components as global variables for your frame or panel or at least you have methods to get them.
public class UIHelper extends JFrame {
Student student = new Student();
JButton btnAction;
JTable myTable;
public UIHelper() {
//Methods for creating UI
//.
//.
//.
student.setId("stackoverflowed");
student.setTakenCourses(new ArrayList<Course>());
btnAction = new JButton("Action!");
//Methods of the JButton (...)
btnAction.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Now just process since student is a global variable (you can set it static as well) but it shouldn't be a good practice at all
for (Course course : student.getTakenCourses()) {
System.out.println(course.getName());
//Add the element to your table.
}
}
});
}
public static void main(String[] args) {
//Assume this is your UI
new UIHelper();
}
Hope I give you an idea, best regards.

Categories

Resources