How to access the value of string by the inheritance? - java

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);
}
}
}

Related

Creating a method that creates multiple lists inside a class

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

Java: Access class within a method

I would like have one method declare two Strings and assign them values. Then have another method to read those values.
I have this structure:
public class ABC extends CDE implements EFG {
public void firstMethod(valueOne, valueTwo) {
class TestClass {
public String testValue = valueOne;
public String anotherValue = valueTwo;
}
}
public void readMethod() {
// HERE I WANT TO READ testValue AND ASSIGN IT A NEW VALUE
}
}
How can I do that?
And is there a better way?
Are you sure you need a class?
May be a simple field declaration will be enough:
public class ABC extends CDE implements EFG {
public String testValue;
public String anotherValue;
public void firstMethod(String valueOne, String valueTwo) {
// do whatever you wish with testValue and anotherValue
}
public void readMethod() {
// here you have access to both variables
}
}
Make the local class global and set/read values via instance:
public class ABC extends CDE implements EFG {
class TestClass {
public String testValue = valueOne;
public String anotherValue = valueTwo;
}
private testClassInstance = new TestClass()
public void firstMethod(valueOne, valueTwo) {
testClassInstance.testValue = valueOne
testClassInstance.anotherValue = valueTwo
}
public void readMethod() {
System.out.println(testClassInstance.valueOne)
System.out.println(testClassInstance.valueTwo)
}
}
All you want to do is to create a POJO that holds testValue and anotherValue and declare the class outside of your component class, e.g.:
class ExampleBean {
private String testValue;
private String anotherValue;
//getters and setters
}
Once done, you can hold the reference of that class into your component class and access the value, e.g.:
public class ABC extends CDE implements EFG {
ExampleBean exampleBean = new ExampleBEan();
public void firstMethod(valueOne, valueTwo) {
exampleBean.setValueOne(valueOne);
exampleBean.setAnotherValue(valueTwo);
}
public void readMethod() {
String value = exampleBean.getValueOne();
}
}
Maybe this will fit your criteria?
What you are currently asking for is impossible due to the scope of the inner class.
You could also initialize this private class instance in your constructor.
public class Sample {
class TestClass {
public String testValue;
public String anotherValue;
}
private TestClass localTest = new TestClass();
public void firstMethod(valueOne, valueTwo) {
localTest.testValue = valueOne;
localTest.anotherValue = valueTwo;
}
public void readMethod() {
localTest.testValue = "test1";
localTest.anotherValue = "anotherValue";
System.out.println(localTest.testValue);
}
}
You are declaring a class withing a method , which is not right
You need to understand what a class and a method really mean ( Google Java OOP ) :
1- You should create a class and declare the variables you want
2- make constructors for the default values
3- make setters to set (assign) these values
4- make getters to read those values

Why couldn't I deal with argument in java?

I'm java virgin. I've made really simple code like below.
class TreeData implements Comparable<TreeData> {
private String sixString;
private ArrayList<Integer> stringNum = new ArrayList<Integer>();
private ArrayList<Integer> charNum = new ArrayList<Integer>();
public TreeData(String sixString, int stringNum, int charNum){
this.sixString = sixString;
(this.stringNum).add(stringNum);
(this.charNum).add(charNum);
}
public int compareTo(TreeData other) {
return sixString.compareTo(other.getSixString());
}
public String getSixString(){
return sixString;
}
}
class Child<T extends Comparable<T>>{
public void print(T data){
//error : String a = data.getSixString();
System.out.println("hi");
}
}
public class Test {
public static void main(String[] args) {
Child<TreeData> child = new Child<TreeData>();
TreeData td = new TreeData("sixString", 8, 2);
child.print(td);
}
}
I had a problem in 'print' method in the Child class. When I tried calling the getSixString() method of data(passed as argument), it occurs error. I don't know why I can't using public method in the argument 'data'. Is it related with Generic? Thanks, in advance.
In your Child class, you only define T to be extending Comparable. Yet you expect it to have the method getSixString which Comparable doesn't have. What you probably want it for it to be extending TreeData:
class Child<T extends TreeData>{
public void print(T data){
String a = data.getSixString();
//should work now since T defines getSixString()
}
}
Or better yet if all you want is for T to be TreeData, you don't need any generic class. I'm assuming your real intention was:
class Child extends TreeData {
public void print(){
String a = getSixString();
}
}

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

Loop through hashmap to create a class instance with inside functions

I am making a bukkit plugin, and I am using an API called MCStats, to create the graph, you add Plotters like so...
mobs.addPlotter(new Metrics.Plotter("Player") {
#Override
public int getValue() {
return 0;
}
});
But I want to get the values from a HashMap, and idealy something like this...
for(String mob: mobNames) {
mobs.addPlotter(new Metrics.Plotter(mob) {
#Override
public int getValue() {
return Stats.getValue(mob);
}
});
}
But obviously, it can't access the mob variable, if I set it to final, it still wont be able to change in the loop. How can I work around this problem?
You can, in fact, use final in an enhanced for loop:
for(final String mob: mobNames) {
mobs.addPlotter(new Metrics.Plotter(mob) {
#Override
public int getValue() {
return Stats.getValue(mob);
}
});
}
You can use the final keyword for mob and it still be changed in the loop.
Try to run this code below:
public class Test2 {
public static void main(String args[]) {
String[] data = new String[] {"1", "2"};
List<MyClass> test = new ArrayList<MyClass>();
for (final String word: data) {
test.add(new MyClass() {
#Override
public void testMethod() {
System.out.println(word);
}
});
}
for (MyClass myClass: test) {
myClass.testMethod();
}
}
static class MyClass {
public void testMethod() {
}
}
}
The output will be "1" and "2".

Categories

Resources