Creating a method that creates multiple lists inside a class - java

i wanted to know if you can create a method inside a class that can create more than 1 list
public class UnidadeSaude {
private String NomeUnidade;
public UnidadeSaude() {
}
public UnidadeSaude(String NomeUnidade) {
this.NomeUnidade = NomeUnidade;
}
public String getNomeUnidade() {
return NomeUnidade;
}
public void setNomeUnidade(String nomeUnidade) {
NomeUnidade = nomeUnidade;
}
void gravar(String NomeUnidade){
List<String> UnidadeSaude = new ArrayList<String>();
UnidadeSaude.add(NomeUnidade);
}
void ler() {
System.out.print(UnidadeSaude);
}
}

First: in Java, variable names are written in camelCase and Classes in PascalCase.
This is extremely important to difference between objects and Class references.
Second: I think you're trying to write names into a List in the gravar() method.
You can do it by having a static List in the class. You can add them to the list and then print them in the ler() method.
public class UnidadeSaude {
private String nomeUnidade;
private static List<String> nomeUnidades = new ArrayList();
public UnidadeSaude() {
}
public UnidadeSaude(String nomeUnidade) {
this.nomeUnidade = nomeUnidade;
}
public String getNomeUnidade() {
return nomeUnidade;
}
public void setNomeUnidade(String nomeUnidade) {
this.nomeUnidade = nomeUnidade;
}
void gravar(String NomeUnidade) {
nomeUnidades.add(NomeUnidade);
}
void ler() {
for (String nome : nomeUnidades) {
System.out.println(nome);
}
}
}
HOWEVER, I don't recommend this! It doesn't semantically make sense to store multiple objects into a class that represents a single object. You should ideally store them in a List outside that class

Related

How to access the value of string by the inheritance?

import java.util.*;
class Pilot
{
protected String PILOT = "BSIT-1A";
public static void Subject()
{
String[] subs = {"Comprog11","WebDev","Digilog12","ComProg12"};
}
public static void Teacher()
{
String[] teach = {"Ms.a","Ms.b","Ms.c","Ms.d"};
}
}
class Pilot1 extends Pilot
{
protected String PILOT1 = "BSIT-1B";
public static void main(String[]args)
{
Pilot1 obj = new Pilot1();
System.out.println(obj.PILOT);
System.out.println(obj.PILOT1);
obj.Subject();
obj.Teacher();
}
how to display the values of Subject() and Teacher() if I put inside it a String?It doesnt have any compiler issues but when I ran it display only the
BSIT-1A
BSIT-1B
my expected output is
BSIT-1A
BSIT-1B
Comprog11
Webdev
Digilog12
Comprog12
Ms.a
Ms.b
Ms.c
Ms.d
You can return the array
public String[] subject() {
return {"Comprog11","WebDev","Digilog12","ComProg12"};
}
Then remove the inheritance. You don't need it for the main method. Make the pilot constants public or pass those strings into a class constructor and add a private field with a getter method, for example
Pilot a = new Pilot("BSIT-1A");
Pilot b = new Pilot("BSIT-1B");
System.out.println(a.getCode());
System.out.println(b.getCode());
Arrays.stream(a.subject()).forEach(System.out::println);
You need the either print the values in Subject() and Teacher() or make them return the values. Also calling static methods via objects is not a
good practice. They should be invoked by the class, like Pilot1.Subject().
class Pilot
{
protected String PILOT = "BSIT-1A";
public static void Subject()
{
String[] subs = {"Comprog11","WebDev","Digilog12","ComProg12"};
for(String sub : subs){
System.out.println(sub);
}
}
public static void Teacher()
{
String[] teach = {"Ms.a","Ms.b","Ms.c","Ms.d"};
for(String t : teach){
System.out.println(t);
}
}
}

Method not available in Generic Return Object

I am trying to access the method GetDatbaseName(), from the returned object obj, but it is returning error that the method is not available.
However, when I Typecast the obj, it is working.
String name = ((Oracle)obj).GetDatabaseName();
How to handle this generic? Like I can't typecast for each return type like Oracle and MongoDB. Also any better implementation for this?
// one class needs to have a main() method
public class HelloWorld
{
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
Data dt = new Data("Oracle");
Object obj = dt.GetObject();
String name = obj.GetDatabaseName();
System.out.println(name);
}
}
public class Data
{
public String _type;
public Data(String type)
{
_type = type;
}
public Object GetObject()
{
Object obj = null;
switch(_type)
{
case("Oracle"):
obj = new Oracle("Test");
break;
case("MongoDB"):
obj = new MongoDB("TestCollection");
break;
}
return obj;
}
}
public class Oracle
{
public String _databaseName;
public Oracle(String databaseName)
{
_databaseName = databaseName;
}
public String GetDatabaseName() { return _databaseName; }
}
public class MongoDB
{
public String _collectionName;
public MongoDB(String collectionName)
{
_collectionName = collectionName;
}
public String GetCollectionName() { return _collectionName; }
}
There are two ways to solve this, the first is using a generic class, while the second is using interface, the second approach is better if you know that the classes will have the same methods, while the generic approach is if the classes have different methods
Generic approach
public class DBtest{
public static void main(String[] args){
DataBase<Oracle> database = new DataBase<>(Oracle.class);
Oracle oracle = database.getDataBase();
System.out.println(oracle.getDatabaseName());
}
}
class DataBase<T>{
private T database;
public DataBase(Class<T> classOfT){
try {
database = classOfT.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public T getDataBase(){
return database;
}
}
class Oracle{
private String _databaseName;
public Oracle(){
_databaseName = "test";
}
public String getDatabaseName() { return _databaseName; }
}
As you can see, it is not possible to define the name of the database, this would be possible of you write <T extends Name> which is an interface which has getName() and setName() method
Interface approach
public class DBtest{
// arguments are passed using the text field below this editor
public static void main(String[] args){
DataBase database = new DataBase(new Oracle("test"));
DatabaseName databaseName = database.getDataBase();
System.out.println(databaseName.getName());
}
}
interface DatabaseName {
String getName();
}
class DataBase{
private DatabaseName databaseName;
public DataBase(DatabaseName databaseName){
this.databaseName = databaseName;
}
public DatabaseName getDataBase(){
return databaseName;
}
}
class Oracle implements DatabaseName {
private String _databaseName;
public Oracle(String name){
_databaseName = name;
}
public String getName() {
return _databaseName;
}
}
class MongoDB implements DatabaseName {
private String _databaseName;
public MongoDB(String name){
_databaseName = name;
}
public String getName() {
return _databaseName;
}
}
Obviously DatabaseName is a bad name for an interface, but it is the only method which is the same for both classes, so it makes sense to call it that. The great thing about interfaces is that you don't have to give a shit about what class is used as long as you know the method names.
You problem is on the following lines:
Object obj = dt.GetObject();
String name = obj.GetDatabaseName();
As far as those lines are concerned, obj is of type Object, which does not have the invoked method; thus, the issue. This is due to Java being strongly typed.
To go around that, you need a type that has this method, or use reflection. To use a type that has this method, they need to inherit it from a common parent of implement it from a common interface. You can also wrap you objects or a bunch of other alternatives.
In your case, it seems that a common interface is the easiest way to go. In this case, each class should implement this interface and instead of using Object your reference would be of the type of that interface.
public Object GetObject()
Would become
public MyInterface GetObject()
and
public class Oracle
would be
public class Oracle implements MyInterface
Where MyInterface would declare the method
public interface MyInterface {
String GetDatabaseName();
}
Being mindful of Java conventions, methods should start with lowercase
public interface MyInterface {
String getDatabaseName();
}
In the case where you cannot change the code in order to implements those methods, you can use "instanceof" to test against the class type.
name = (obj instanceof Oracle)?((Oracle)obj).GetDatabaseName():((MongoDB )obj).getCollectionName();
You must have to create an Interface and then with getDatabaseName() method. Then your objects Oracle and MongoDB must implement that interface.
What you are trying to do is something similar to AbstractFactory Pattern. You should google it.
public interface MyDbInterface {
String getDatabaseName();
}
public class HelloWorld {
// arguments are passed using the text field below this editor
public static void main(String[] ){
MyDbInterface dt = DataFactory.create("Oracle");
String name = dt.getDatabaseName();
System.out.println(name);
}
}
public final class DataFactory{
private DataFactory(){
super();
}
public static MyDbInterface create(String type){
MyDbInterface obj = null;
switch(type) {
case("Oracle"):
obj = new Oracle("Test");
break;
case("MongoDB"):
obj = new MongoDB("TestCollection");
break;
}
return obj;
}
}
public class Oracle implement MyDbInterface{
public String databaseName;
public Oracle(String databaseName){
databaseName = databaseName;
}
#Override
public String getDatabaseName() {
return databaseName;
}
}
public class MongoDB implement MyDbInterface{
public String collectionName;
public MongoDB(String collectionName){
collectionName = collectionName;
}
public String getCollectionName() {
return collectionName;
}
#Override
public String getDatabaseName() {
return getCollectionName();
}
}
I suposed you come from C#, check java style guide. ;)
You should think about the design of your code. You need to use basic OOP principal to solve the problem. There are several ways to solve your problem like using interface/generics etc. Here I am giving one such example.
public class HelloWorld {
public static void main(String[] args) {
Data dt = new Data("Oracle");
DataBase obj = dt.GetObject();
String name = obj.getDatabaseName();
System.out.println("Name : "+name);
}
}
class Data {
public String _type;
public Data(String type) {
_type = type;
}
public DataBase GetObject() {
DataBase dataBase=null;
switch (_type) {
case "Oracle":
dataBase = new Oracle();
break;
case "Mongo":
dataBase = new MongoDb();
break;
}
return dataBase;
}
}
interface DataBase {
String getDatabaseName();
}
class Oracle implements DataBase {
public String getDatabaseName() {
return "Oracle";
}
}
class MongoDb implements DataBase {
public String getDatabaseName() {
return "Mongo";
}
}
Edited:
Here is another way to solve your problem. I believe this approach might solve your problem.
public class HelloWorld {
public static void main(String[] args) {
Data<Oracle> dt = new Data<Oracle>("Oracle");
Oracle obj = dt.getObject();
String name = obj.getDatabaseName();
System.out.println("Name : "+name);
}
}
class Data<T> {
public String _type;
public Data(String type) {
_type = type;
}
public T getObject() {
Object dataBase=null;
switch (_type) {
case "Oracle":
dataBase = new Oracle();
break;
case "Mongo":
dataBase = new MongoDb();
break;
}
return (T)dataBase;
}
}
class Oracle {
public String getDatabaseName() {
return "Oracle";
}
}
class MongoDb {
}

How to pass down the new operator in a method

For example, if I wanted to do something like this to call a method:
myLights.addLight(new Fluorescent(lumens));
in order to create a new object in the Fluorescent class and pass down the lumens data. How would I then set up the method to receive this?
Assuming method is not returning anything.
void addlight(Fluorescent a){
// your logic
}
In your Lights class create a method that accepts a Fluorescent object as an argument.
public void addLight(Fluorescent fluorescent){
// do something
}
Here is a basic example:
public class HelloWorld
{
public static void main(String[] args)
{
Light light = new Light();
light.addLight(new Fluorescent("300 lm"));
System.out.print(light.getLumen());
}
}
public class Light {
private String lumen;
public Light() {
}
public void setLumens(String lumen){
this.lumen = lumen;
}
public String getLumen(){
return this.lumen;
}
public void addLight(Fluorescent fluorescent) {
if(fluorescent.getLumen() != null) {
this.lumen = fluorescent.getLumen();
}
}
}
public class Fluorescent {
private String lumen;
public Fluorescent(String lumen){
this.lumen = lumen;
}
public void setLumen(String lumen){
this.lumen = lumen;
}
public String getLumen(){
return this.lumen;
}
}
Seeing that a Fluorescent is a Light, you might want to look in to inheritance.
Look here for some explanation
Java 101: Inheritance in Java, Part 1
public class Fluorescent() {
public Fluorescent(String lumens) {
// do something
}
}
public class Lights() {
public void addLight(Fluorescent fluorescent) {
// do something
}
}

Declaring a nested class in Java

I'm a bit confused with subclasses.
Here's my code:
public class MedHistory {
private String grafts;
private String allergies;
private String diseases;
private String surgeries;
private String medicalTreatment;
//Constructors (#2)
public MedHistory(String allergies, String diseases, String grafts,
String treatments, String surgeries) {
this.allergies=allergies;
this.diseases=diseases;
this.grafts=grafts;
this.medicalTreatment=treatments;
this.surgeries=surgeries;
}
public MedHistory() {
this.allergies="";
this.diseases="";
this.grafts="";
this.medicalTreatment="";
this.surgeries="";
}
//Getters
public String getGrafts() {
return grafts;
}
public String getAllergies() {
return allergies;
}
public String getDiseases() {
return diseases;
}
public String getSurgeries() {
return surgeries;
}
public String getMedicalTreatment() {
return medicalTreatment;
}
//Setters
public void setGrafts(String grafts) {
this.grafts = grafts;
}
public void setAllergies(String allergies) {
this.allergies = allergies;
}
public void setDiseases(String diseases) {
this.diseases = diseases;
}
public void setSurgeries(String surgeries) {
this.surgeries = surgeries;
}
public void setMedicalTreatment(String medicalTreatment) {
this.medicalTreatment = medicalTreatment;
}
public class FemMedHistory extends MedHistory {
private List<Birth> births = new ArrayList<Birth>();
//Constructors (#2)
public FemMedHistory(String allergies, String diseases, String grafts,String treatments, String surgeries, List<Birth> birthlist) {
super(allergies,allergies,grafts,treatments,surgeries);
this.births=birthlist;
}
public FemMedHistory() {
super();
this.births=null;
}
//Getter
public List<Birth> getBirths() {
return this.births;
}
//Setter
public void setBirths(List<Birth> list) {
this.births=list;
}
}
}
When I try to create an new FemMedHistory object like this:
List<Birth> list = new ArrayList<Birth>();
list.add(new Birth(new GregorianCalendar(2011,4,10),"kaisariki",4));
FemMedHistory female = new FemMedHistory("allergia2","astheneia2","emvolia2","farmekeutiki agwgi2", "xeirourgeia2", list);
I get the error:
No enclosing instance of type MedHistory is accessible. Must qualify
the allocation with an enclosing instance of type MedHistory (e.g.
x.new A() where x is an instance of MedHistory).
So, which is the right way to use a subclass?
When you declare a nested class it only available through the Outer class.
To access it outside, you will need to either make the FemMedHistory class static.
public static class FemMedHistory extends MedHistory {...}
access it through the MedHistory class
MedHistory.FemMedHistory myMedHistory = ...
or declare it in it's own Java file.
You have declared your subclass as an inner class, which means that you can't create an instance of it without first creating an instance of the containing class.
The most common way to solve this is to declare it as a separate class, which would get rid of your error.
Long story short: cut all the FemMedHistory code and paste it into FemMedHistory.java. The way it is now you have involved Java concepts which you have not yet mastered. Also, that class really does belong in a separate file.

Conflict between passing an Array from Main Class to Function, but also wanting to use return vales from my "getter" method

In my main class, I have a static method which I pass the array into. It is a static method because if I want to pass something from the main class body to this method, it must be static. In a separate class I have a series of getters and setters (which must be non static ).
How can I pass my static array in and use the non-static getters and setters?
EDIT- In the arraySearch method...I cannot pass in the Person Array and access the getters in the Person Class
public class Main {
public static void main(String[] args) {
Person One = new Person("Alice","Foo", 22, false);
Person Two = new Person("Alice", "Foo",22, false);
Person Three = new Person("Bob","Bar",99, false);
Person Four = new Person("Joe","Blogs",64, false);
Person Five = new Person("Jane", "Joe",42, false);
Person [] People = {One,Two,Three,Four,Five};
printArray(People);
}
public static void printArray(Person [] People)
{
for(int i=0;i<People.length;i++)
{
System.out.println(People[i]);
}
}
public void arraySearch(Person [] People)
{
for(int i=0;i<People.length;i++) //Searches the Array of Objects
{
String firstName = Person.getFirstName();
String secondName=Person.getSecondName();
if((firstName.equals("Joe")&&secondName.equals("B" + //Searches for Joe Blogs and Jane Joe
"logs"))|| ((firstName.equals("Ja" +
"ne")&&secondName.equals("Joe"))))
{
int age=Person.getAge();
Person.setAge(age+1); //Increments Age by 1
}
}
}
}
public class Person {
private String mfirstName;
private String msecondName;
private int mage;
private boolean misRetired;
public Person(String firstName,String secondName,int age, boolean isRetired)
{
mfirstName=firstName;
msecondName=secondName;
mage=age;
misRetired=isRetired;
}
//GETTERS
public String getFirstName()
{
return mfirstName;
}
public String getSecondName()
{
return msecondName;
}
public int getAge()
{
return mage;
}
public boolean getRetired()
{
return misRetired;
}
//SETTERS
public void setFirstName(String firstName)
{
mfirstName=firstName;
}
public void setSecondName(String secondName)
{
msecondName=secondName;
}
public void setAge(int age)
{
mage=age;
}
public void setRetired(boolean isRetired)
{
misRetired=isRetired;
}
//STRING
public String toString()
{
return (mfirstName+"-"+msecondName+"-"+mage+"-"+misRetired);
}
}
This is very basic Java question. You need to create instance of object containing setter/getters from your static method. You can also pass static array in setter of this object. Then you should be able to call those getter/setter methods.
public class Main
{
public static void main(String[] args)
{
MyClass myclass = new MyClass();
myclass.setArgs(args);
System.out.println(myclass.getArgs());
}
}
public class MyClass
{
private String[] args;
public String[] getArgs()
{
return args;
}
public void setArgs(String[] args)
{
this.args= args;
}
}
You have to create an object instance from the class with the getters.
The Amit answer is correct; this just has some more info and more closely matches the situation you describe in your question.
Your basic premise "It is a static method because if I want to pass something from the main class body to this method, it must be static." is wrong. The method to which you pass the array does not need to be static. Here is some code:
public final class Main
{
private static final String[] staticOTron =
{
"one",
"two",
"three"
};
public static void main(final String[] args)
{
String[] hootBerrySause;
Tool tool = new Tool();
tool.setStaticOTron(staticOTron);
hootBerrySause = tool.getStaticOTron();
for (String value : hootBerrySause)
{
System.out.println("Value: " + value);
}
}
}
// this can be in a different file.
public final class Tool
{
private static String[] staticOTron;
public void setStaticOTron(final String[] newValue)
{
staticOTron = newValue;
}
public String[] getStaticOTron()
{
return staticOTron;
}
}
Sunil kumar from vmoksha
Your asking deeper navigation
Just create the instance of particular or create the getter &and setter in the main
class

Categories

Resources