I have a class like this..
public static class FlightInfoDetails {
static String FlightNumber;
static String DepartureDate;
static String DepartureTime;
public static void setFlightNumber(String pstrData) {
FlightNumber= pstrData;
}
public static void setDepartureDate(String pstrData) {
DepartureDate = pstrData;
}
public static void setDepartureTime(String pstrData) {
DepartureTime = pstrData;
}
public static String getFlightNumber()
{
return FlightNumber;
}
public static String getDepartureDate()
{
return DepartureDate;
}
}
And so on. Everything was fine up to this, but now I need to deal with multiple number of
FlightInfoDetails. When I tried to call that set method the previous data gets lost. Can anybody help?
First off, if you want to be able to create many instances of the FlightInfoDetails class, you should get rid of the static modifiers you have.
public class FlightInfoDetails {
String FlightNumber;
String DepartureDate;
String DepartureTime;
public void setFlightNumber(String pstrData) {
FlightNumber= pstrData;
}
public void setDepartureDate(String pstrData) {
DepartureDate = pstrData;
}
public void setDepartureTime(String pstrData) {
DepartureTime = pstrData;
}
public String getFlightNumber()
{
return FlightNumber;
}
public String getDepartureDate()
{
return DepartureDate;
}
}
Now you shouldn't have any issues creating more than one FlightInfoDetails object, or setting the data for each object. In a main method, you can create an ArrayList of these objects.
public static void main(String [] args)
{
ArrayList<FlightInfoDetails> flightList = new ArrayList<FlightInfoDetails>():
FlightInfoDetails info = new FlightInfoDetails();
flightList.add(info);
FlightInfoDetails info2 = new FlightInfoDetails();
flightList.add(info2);
info.setDepartureDate("May 20, 2013");
info2.setDepartureDate("June 10, 2013");
}
Add a new instance of your FlightInfoDetails class.
FlightInfoDetails details = new FlightInfoDetails();
Call setter methods as necessary on this instance.
details.setDepartureDate("12/12/2013");
Store this instance in a List:
List<FlightInfoDetails> detailsList = new ArrayList<FlightInfoDetails>();
detailsList.add(details);
Note: Ensure you remove all static modifiers from your FlightInfoDetails class so that you can create instances of this class.
Related
The code is incomplete at the moment, but I was wondering if I could use the String partNo the one that the constructor is making inside the mutator.
public static class Invoice{
Scanner sam = new Scanner(System.in);
int Quality;
double price;
public Invoice(){
}
public Invoice(String partNo, String description) {
}
public void setPartNo() {
System.out.println("Enter part no: ");
String partNo = sam.nextLine();
}
public static String getPartNo() {
return Invoice.getPartNo();
}
}
public static void main(String[] args) {
Invoice.getPartNo();
public static class Invoice{
Scanner sam = new Scanner(System.in);
int Quality;
double price;
public Invoice(){
}
public Invoice(String partNo, String description) {
}
public void setPartNo() {
System.out.println("Enter part no: ");
String partNo = sam.nextLine();
}
public static String getPartNo() {
return Invoice.getPartNo();
}
}
public static void main(String[] args) {
Invoice.getPartNo();
You here have a few parameters to your constructor, you don't do anything with, which is pretty pointless. They won't exist anymore once the constructor has finished executing, so it's impossible for your mutators to get them
Those parameters, set them up as instance members, that way your mutators will also have access to them.
public static class Invoice {
Scanner sam = new Scanner(System.in);
int quality;
double price;
// add the additional instance members
String partNo;
String description;
public Invoice() { }
public Invoice(String partNo, String description) {
this.partNo = partNo;
this.description = description;
}
// a normal mutator (setter) will not use a Scanner, but accept the value as parameter
// but for now, I'm keeping your original design
public void setPartNo() {
System.out.println("Enter part no: ");
this.partNo = sam.nextLine();
// again, use this.partNo. If you declare it as a String here, it will no longer exist when the method is finished
}
// this getter is both pointless, and will cause trouble by creating an endless
// recursive loop. Delete it.
public static String getPartNo() {
return Invoice.getPartNo();
}
}
Now, the same code with some improvements:
public static class Invoice {
int quality;
double price;
// add the additional instance members
String partNo;
String description;
public Invoice() { }
public Invoice(String partNo, String description) {
this.partNo = partNo;
this.description = description;
}
public void setPartNo(String partNo) {
// you can always add validation on the new value here
this.partNo = partNo;
}
public String getPartNo() {
return partNo;
}
}
this, you will be able to use as follows:
public static void main(String[] args) {
Invoice in = new Invoice("part", "description");
System.out.pintln(in.getPartNo());
in.setPartNo("new PartNo");
System.out.println(in.getPartNo());
}
If you are wondering whether your getter should be static:
it should only be static if the field is static itself. Since you set the value by a parameter you pass to the constructor, it is doubtfull it should be static.
A parameter to the constructor should (usually) only set the value for that particular instance.
If it's a static field, it will be set for every single instance of that type.
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);
}
}
}
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
I am completely new to Java... :(
I need to pass a variable from a parent class to a child class, but I don't know how to do that.
The variable is located in a method in the parent class and I want to use it in one of the methods of the child class.
How is this done?
public class CSVData {
private static final String FILE_PATH="D:\\eclipse\\250.csv";
#Test
public static void main() throws IOException {
//some code here
String firstname1 = array.get(2).get(1);
}
}
and then the other class
public class UserClassExperimental3 extends CSVData {
public static void userSignup() throws InterruptedException {
//some code here
String firstname= firstname1; //and here it doesnt work
}
}
Actually I think I succeeded doing that this way:
added the variable here:
public static void userSignup(String firstname1)
then used it here:
String firstname=firstname1;
System.out.println(firstname);
But now I can't pass it to the method that needs it.
The variable firstname1 is a local variable. You can't access it outside its scope - the method.
What you can do is pass a copy of the reference to your subclass.
Since you're calling a static method, the easiest way is to pass the reference as an argument to the method call:
#Test
public static void main() throws IOException {
//some code here
String firstname1 = array.get(2).get(1);
UserClassExperimental3.userSignup( firstName1 );
}
public class UserClassExperimental3 extends CSVData {
public static void userSignup( String firstNameArg ) throws InterruptedException {
//some code here
String firstname = firstnameArg; // Now it works
}
}
That said, since you're using inheritance, you might find it useful to use an instance method. Remove "static" from the method. In main(), construct an instance of the class, provide it the name, and call the method on the instance.
#Test
public static void main() throws IOException {
//some code here
String firstname1 = array.get(2).get(1);
UserClassExperimental3 instance = new UserClassExperimental3( firstName1 );
instance.userSignup();
}
public class UserClassExperimental3 extends CSVData {
private String m_firstName;
public UserClassExperimental3( String firstName ) {
m_firstName = firstName;
}
public void userSignup() throws InterruptedException {
//some code here
String firstname = m_firstname; // Now it works
}
}
If you also add userSignup() to the CSVData class, you can refer to the specific subclass only on creation. This makes it easier to switch the implementation, and it makes it easier to write code that works regardless of which subclass you're using.
String firstname1 = array.get(2).get(1);
CSVData instance = new UserClassExperimental3( firstName1 );
instance.userSignup();
public class Main {
public static void main(String[] args) {
User user=new User();
user.setId(1);
user.setName("user");
user.setEmail("user#email.com");
user.save();
}
}
public class User extends Model {
private int id;
private String name;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
import java.lang.reflect.Field;
public class Model {
public void save(){
for(Field field: Model.this.getClass().getDeclaredFields()) {
field.setAccessible(true);
try {
System.out.println(field.getName()+"="+field.get(Model.this));
} catch (Exception ex) {
ex.printStackTrace();
}
}
return;
}
}
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