how to retrieve an array into one class from a different class - java

I have a class where I made an array of the planets.
private final static Planet[]
{
new Planet("Mercury"),
new Planet("Venus"),
new Planet("Earth"),
new Planet("Mars"),
new Planet("Jupiter"),
new Planet("Saturn"),
new Planet("Uranus"),
new Planet("Neptune")
};
and I need to retrieve it into another class.
public float getPlanetMass()
{
}
How exactly would I go about this?

You can have a public method in a class to return the planets and another class that will call that method to get the list. Something like below :
public class Test {
private Planet[] getPlanets(){
Planet[] planets = new Planet[8];
int index = 0;
for(String name : Arrays.asList("Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune")) {
planets[index++] = new Planet(name);
}
return planets;
}
static class PlanetClient{
public static void main(String args[]) {
Test test = new Test();
Planet[] planets = test.getPlanets();
System.out.println("Planets are " + Arrays.toString(planets));
}
}
class Planet {
String name;
Planet(String name){
this.name = name;
}
#Override
public String toString() {
return this.name;
}
}
}

There are a lot of ways to do this but instead of creating an array you could create an Enum called Planet or even an enum called StandardPlanet or TerrestialPlanet that implements an interface called Plant. This way the enum uses the multiton pattern, you can reference these elements publicly, and you're not creating non-private mutable objects.
public interface Planet {
}
public enum TerrestialPlanet implements Plant {
EARTH,
MARS,
// etc
}
Planet planet = TerrestialPlanet.EARTH;

Related

Java: how can I put new object into array of objects of its class inside a constructor function? Is it possible?

everyone! I'm total noob in Java and in programming in general and I want to implement CarBrand class with its' inner Model class (let there be no more than 4 models for each brand). For example:
public class CarBrand {
public String brand;
public Model[4] models;
public int curIndex = 0;
public CarBrand(String name) {
brand = name;
Model[] models = new Model[4];
}
public class Model {
public String modelName;
public Model(String name) {
modelName = name;
models[curIndex] = this;
curIndex = curIndex + 1;
}
}
}
I want to make new instance of CarBrand and its new Model (and add this model into models array of new instance of CarBrand) this way:
public class App {
public static void main(String args[]) {
CarBrand subaru = new Auto("Subaru");
CarBrand.Model legacy = subaru.new Model("Legacy");
System.out.println(subaru.models[0]);
}
}
But unfortunately running App finishes with error:
Exception in thread "main" java.lang.NullPointerException: Cannot store to object array because "<parameter1>.models" is null
What is the reason behind that? Is there a way to add a new model in brand's models array? I suppose, the object wasn't created yet, that's why there is an error. How far am I from the truth?
Your syntax is generally incorrect: you would need
public Model[] models; // not Model[4]
public int curIndex = 0;
public CarBrand(String name) {
brand = name;
models = new Model[4]; // not Model[]
}

Can you declare class name as an attribute of another class in Java?

I have a class called Television and the second class is called Televisionshop and has Television[] television as an array attribute. And also a constructor called Televisionshop(Television [] television). How can I initialize the attribute to this constructor. ?
class Television {
String name;
Television(String name) {
this.name = name;
}
}
class TelevisionShop {
public Television[] televisions;
TelevisionShop(Television[] televisions) {
this.televisions = televisions;
}
}
public class Main
{
public static void main(String[] args) {
Television t1 = new Television("t1");
Television t2 = new Television("t2");
Television[] televisions = {t1,t2};
TelevisionShop shop = new TelevisionShop(televisions);
}
}
I guess this is the most straightforward way.

Using a Java For-Each Loop to iterate over an ArrayList which has private access?

I have three classes: Labradors, Kennels and Show. The Kennel contains a private ArrayList of
Labradors. As shown:
Labradors.java:
public class Labradors {
private String name;
private String description;
public Labradors(String n, String d) {
name = n;
description = d;
}
public String getName() {
return name;
}
}
Kennel.java:
import java.util.ArrayList;
public class Kennel{
private ArrayList<Labradors> labs;
public Kennel() {
labs = new ArrayList<Labradors>();
}
public void addDog(Labradors l) {
labs.add(l);
}
}
and
Show.java
class Show
{
public static void main(String args[])
{
Labradors Dave = new Labradors("Dave", "Good dog!");
Labradors Bob = new Labradors("Bob", "Likes tummy rubs!");
Kennel niceHome = new Kennel();
niceHome.addDog(Dave);
niceHome.addDog(Bob);
for (Labradors lab: niceHome.labs ) {
System.out.println(lab.getName());
}
}
}
My for-each loop in Show gives me the following error:
Show.java:12: error: labs has private access in Kennel
for (Labradors lab: niceHome.labs ) {
^
1 error
Clearly one solution would be to make the ArrayList public, but my understanding of encapsulation is that best practice means it should be private and a Getter written. But how do I do this?
I feel this should have a really easy answer, but I'm having difficulty tracking it down...
NB - I'm using openjdk version 11.0.6 on Ubuntu 19.10.
Inside Kennel Class make a getter function
import java.util.ArrayList;
public class Kennel{
private ArrayList<Labradors> labs;
public Kennel() {
labs = new ArrayList<Labradors>();
}
public void addDog(Labradors l) {
labs.add(l);
}
public ArrayList<Labradors> getLabs(){
return this.labs;
}
}
Then access from main function like this
class Show
{
public static void main(String args[])
{
Labradors Dave = new Labradors("Dave", "Good dog!");
Labradors Bob = new Labradors("Bob", "Likes tummy rubs!");
Kennel niceHome = new Kennel();
niceHome.addDog(Dave);
niceHome.addDog(Bob);
for (Labradors lab: niceHome.getLabs()) {
System.out.println(lab.getName());
}
}
}

How can I access gets and sets in a sub class?

In this application we have the Automovel class:
public class Automovel {
private String marca;
private String matricula;
private String anoConstrucao;
private Motor motor;
private int preco = 0;
}
(with their builders, getters and setters) and there is a class called Motor that is an attribute of the Automovel class.
Motor Class:
private int potencia;
public Motor() {}
public Motor(int potencia){
this.potencia = potencia;
}
public int getPotencia() {return this.potencia;}
public void setPotencia(int potencia) {
this.potencia = potencia
}
There are also 2 subclasses of this class (MotorEletrico and MotorCombustao):
Motor Elétrico:
public class MotorEletrico extends Motor {
private int autonomia;
public MotorEletrico() {}
public MotorEletrico(int potencia, int autonomia) {
super(potencia);
this.autonomia = autonomia;
}
public int getAutonomia() {
return autonomia;
}
public void setAutonomia(int autonomia) {
this.autonomia = autonomia;
}
}
Motor Combustão:
public class MotorCombustao extends Motor{
private int cilindrada;
private String combustivel;
public MotorCombustao(){}
public MotorCombustao(int potencia, int cilindrada, String combustivel){
super(potencia);
this.cilindrada = cilindrada;
this.combustivel = combustivel;
}
public int getCilindrada(){
return cilindrada;
}
public void setCilindrada(int cilindrada){
this.cilindrada = cilindrada;
}
public String getCombustivel(){
return combustivel;
}
public void setCombustivel(String combustivel){
this.combustivel = combustivel;
}
}
I store a car with an X engine in an array of Automovel objects, but when I try to access the getters and setters of the subclass (MotorCombustao / MotorEletrico), only the gets and sets of the mother class (Motor) appears. My problem is that I can't access the getters and setters of the motor subclasses.
Here's an example of what I tried:
Automovel arrayteste[] = new Automovel[49];
Motor motor1 = new MotorEletrico();
motor1.setPotencia(5);
Automovel automovel1 = new Automovel("Opel", "xx-12-xx", "2000", motor1, 2000);
arrayteste[0] = automovel1;
System.out.println(arrayteste[0].getMotor().getPotencia()); //Here, I can't Do .getAutonomia
Short answer
You need to cast
System.out.println(((MotorElettrico)(arrayteste[0].getMotor())).getAutonomia());
TL;DR
When you wrote
Motor motor1 = new MotorElettrico();
you are using polymorphism.
This is very useful when, for example you, have a list of Motor that contains more then one motor type and for all of this you want to print the potencia.
Then you can write something like this:
List<Motor> list = Arrays.asList(new MotorElectico(), new MotorCombustao());
// ----- some set
print(list);
where print method is something like this:
public void print(List<Motor> list){
for(Motor m : list){
System.out.println(String.format("Potencia %d", m.getPotencia()));
}
}
This happens because a MotorElectico IS A Motor and upcasting (casting to supertype) is always allowed.
In your case, you have to do downcasting: you are telling to a compilator that arraytest[0].getMotor() contains a Motor but this Motor is actually a MotorElectrico: you are asking to compilator to trust you. If at compile-time arraytest[0].getMotor() should not be a MotorElectrico you'd get a ClassCastException.
You need to cast the reference of the parent class to the corresponding child class if you want to access a method which is not inherited from the parent class e.g. the method, getAutonomia() is not inherited from Motor and therefore, you need to cast the reference of Motor to MotorEletrico before you can access getAutonomia(). Some more useful code is given below:
public class Main {
public static void main(String[] args) {
Automovel arrayteste[] = new Automovel[2];
Motor motor;
motor = new MotorEletrico(5, 10);
arrayteste[0] = new Automovel("Opel", "xx-12-xx", "2000", motor, 2000);
motor = new MotorCombustao(7, 4, "xx-yy-zz");
arrayteste[1] = new Automovel("Opel", "xx-08-xx", "1995", motor, 1995);
for (Automovel automovel : arrayteste) {
motor = automovel.getMotor();
if (motor instanceof MotorEletrico) {
System.out.println(((MotorEletrico) motor).getAutonomia());
}
if (automovel.getMotor() instanceof MotorCombustao) {
System.out.println(((MotorCombustao) motor).getCilindrada());
System.out.println(((MotorCombustao) motor).getCombustivel());
}
}
}
}
Output:
10
4
xx-yy-zz
[Update: the following update is based on your comment]
Another way to iterate arrayteste is as given below:
for (int i = 0; i < arrayteste.length; i++) {
if (arrayteste[i] != null) {
motor = arrayteste[i].getMotor();
if (motor instanceof MotorEletrico) {
System.out.println(((MotorEletrico) motor).getAutonomia());
}
if (arrayteste[i].getMotor() instanceof MotorCombustao) {
System.out.println(((MotorCombustao) motor).getCilindrada());
System.out.println(((MotorCombustao) motor).getCombustivel());
}
}
}
You are familiar with the Liskov substitution principle, I assume.
If you don't know the type of motor, you can write a statement that asks each instance of the Automovel array arraytest[i] what class it is.
For example:
List<Automovel> arrayteste = new ArrayList<>();
Motor motor1 = new MotorEletrico();
motor1.setPotencia(5);
Automovel automovel1 = new Automovel("Opel", "xx-12-xx", "2000", motor1, 2000);
arrayteste.add(automovel1);
Motor motor = new Motor();
String motorClass;
String[] motorTypes = {"MotorEletrico", "MotorCombustao"};
Set<String> motorClasses = new HashSet<>(Arrays.asList(motorTypes));
for (int i = 0; i < arrayteste.size(); i++)
{
motorClass = arrayteste.get(i).getMotor().getClass().getName();
if (motorClasses.contains(motorClass))
{
if (motorClass.equals("MotorEletrico"))
{
motor = (MotorEletrico)(arrayteste.get(i).getMotor());
}
else if (motorClass.equals("MotorCombustao"))
{
motor = (MotorCombustao)(arrayteste.get(i).getMotor());
}
System.out.println("Automovel #" + i + " : " + motor.getPotencia());
}
else
{
System.out.println("Não sei que classe de motor é esse . . .");
}
}
}
But it might be better to explore the class design more closely.
Possibly try to use interfaces.

How to use Arraylist over different classes

Im trying to add a dog (nyHund) which is created in a different class, to an Arraylist i created using a constructor in another class, but whenever i try to use the Arraylist in the "register" class, im getting the error that the arraylist name can't be resolved.
First class:
public class Hund {
private String namn;
private int ålder;
private double vikt;
private String ras;
public Hund(String hundnamn, int hundålder, String hundras, double hundvikt) {
this.namn = hundnamn;
this.ålder = hundålder;
this.ras = hundras;
this.vikt = hundvikt;
}
public String getNamn() {
return namn;
}
public int getÅlder() {
return ålder;
}
public double getSvanslängd() {
if (ras=="tax"){
return 3.7;
}else{
return ((vikt*ålder)/10);
}
}
public String toString() {
return namn + "\n" + ålder + "\n"+ras+"\n"+vikt+"\n"+getSvanslängd();
}
}
Second Class
import java.util.ArrayList;
public class testning {
public static void main(String[] args) {
Hund nyHund = new Hund("Daisy", 13, "labrador", 22.3);
System.out.println(nyHund.toString());
Register.läggTillHund(nyHund);
}
}
And the Third class:
import java.util.ArrayList;
public class Register {
public static void läggTillHund(Hund nyHund){
hundRegister.add(nyHund);
System.out.println(nyHund);
}
private Register(){
ArrayList<Hund> hundRegister = new ArrayList<Hund>();
}
}
The problem i am experiencing is with "hundRegister.add(nyHund)"
any thoughts? or pointers where im going wrong? (very new at Java)
Best Regards
Oskar
The ArrayList you've created is local to your Register constructor. Declare it inside the class, but outside the constructor, as an instance variable, so it's in scope throughout the class.
public class Register {
private ArrayList<Hund> hundRegister;
private Register(){
hundRegister = new ArrayList<Hund>();
}
}
Additionally, it's unclear why the constructor is private. Nothing else can access that constructor. I would make it public.
Also, in getSvanslängd, replace ras=="tax" with "tax".equals(ras). See How do I compare strings in Java?.

Categories