I would like to create an instance of a class, that has an array of class members within it where the array is defined in length upon initialization. The code I have written does not contain any errors precompile, but after running returns nullPointerException. I want to be able to access products of class storeA by typing storeA.products[productnumber].(product variable), is this possible?
package tinc2;
public class FirstProgram {
public static void main(String[] args) {
store storeA = new store();
storeA.name = "Walmart";
storeA.products = new store.product[3];
storeA.products[0].name = "Horses";
System.out.println(storeA.products[0].name);
}
public static class store{
String name;
product products[];
static class product{
String name;
int quantity;
double price;
}
}
}
Go for
public static void main(String[] args) {
store storeA = new store();
storeA.name = "Walmart";
storeA.products = new store.product[3];
storeA.products[0] = new store.product();
storeA.products[0].name = "Horses";
System.out.println(storeA.products[0].name);
}
instead.
Besides you should place those classes in separate files.
You should follow naming conventions in Java, e.g. Store instead of store.
You should use getters and setters.
I would avoid statics, if it is possible.
You should not be instantiating a static class. Your Product class should not be defined as static. I recommend:
package tinc2;
public class FirstProgram {
public static void main(String[] args) {
Store.name = "Walmart";
Store.products = new Product[1];
Store.products[0] = new Product();
Store.products[0].name = "Horses";
System.out.println(Store.products[0].name);
}
public static class Store{
String name;
Product products[];
}
public class Product{
String name;
int quantity;
double price;
}
}
Related
i have Bank class, with a private static ArrayList that stores all the banks. how can i add every new bank created to it?
i'm not allowed to create any new methods or fields, or change any of the method or constructor parameters.
this is my Bank class:
public class Bank {
private static ArrayList<Bank> allBanks=new ArrayList<Bank>();
private String name;
public Bank(String name) {
this.name = name;
}
public String getName() {
return name;
}
and this is my Main class:
public class Main {
public static void main(String[] args) {
new Bank("randomBankName");
}
}
Do it in constructor:
public Bank(String name) {
this.name = name;
allBanks.add(this);
}
WARNING never do it in real project.
You didn't say, that you may not change the visibility of fields, so that would be one way to do this: make the ArrayList public
If you may not do this either, there is a last way, which i'd never do: Reflection.
In most cases, thats really the last way, not recommended!
I have two classes, Main.java and Car.java
Main.java:
class Main
{
public static void main(String[] args)
{
Car ferrari = new Car(18, 25.43);
System.out.println(ferrari.efficiency);
}
}
Car.java:
class Car
{
public Car(double mpg, double initFuel)
{
double efficiency = mpg;
double fuel = initFuel;
}
}
I obviously tried to assign efficiency to the first constructor passed in when creating the object, but that doesn't seem to work (i.e. the variable is not found when I use the println in Main.java). How do I assign variables to objects to be referenced later?
You're using local variables in your Car's constructor. Their lifecycle bounded within your constructor. Just declare your members in your class and use getters and setters to access them.
class Car
{
private double efficiency;
private double fuel;
public Car(double mpg, double initFuel)
{
this.efficiency = mpg;
this.fuel = initFuel;
}
public void setEfficiency(double efficiency) {
this.efficiency = efficiency;
}
public double getEfficiency() {
return efficiency;
}
// Same thing for fuel...
}
And in your Main:
class Main
{
public static void main(String[] args)
{
Car ferrari = new Car(18, 25.43);
System.out.println(ferrari.getEfficiency());
}
}
Make efficiency and fuel global to your class rather than local to your constructor.
Main.java
public class Main
{
public static void main(String[] args)
{
Car ferrari = new Car(18, 25.43);
System.out.println(ferrari.efficiency);
}
}
Car.java
public class Car
{
public double efficiency;
public double fuel;
public Car(double mpg, double initFuel)
{
efficiency = mpg;
fuel = initFuel;
}
}
That should work. But you can make the instance variables private instead of public and use setters/getters
Also set your Main and Car to public so they can be accessible/instantiated from another class.
Main.java
public class Main
{
public static void main(String[] args)
{
Car ferrari = new Car(18, 25.43);
System.out.println(ferrari.getEfficiency());
}
}
Car.java
public class Car
{
private double efficiency;
private double fuel;
public Car(double mpg, double initFuel)
{
efficiency = mpg;
fuel = initFuel;
}
public double getEfficiency(){
return efficiency;
}
}
Change your Car class to:
class Car
{
private double efficiency;
private double fuel;
public Car(double mpg, double initFuel)
{
this.efficiency = mpg;
this.fuel = initFuel;
}
}
You need to declare the variables on the Class scope instead of the local scope when using a variable for an instantiated Object. These variables typically are set from the Constructor so they can be accessed later from the Object itself.
Most of the time these are also declared as private with a separate method to get and set them instead of directly accessing them.
Example:
public double getEfficiency(){
return this.efficiency;
}
public void setEfficiency(double mpg){
this.efficiency = mpg;
}
Most IDE's can auto generate Getters and Setters for you so you do not need to hand write them for every variable.
To use the getter/setter you call the method from an instance of the class rather than using the variable directly:
Car tesla = new Car(35.5, 90.5);
tesla.efficiency = 15.5; //YOU CAN'T DO THIS
tesla.setEfficiency(15.5); //Do this instead
System.out.println(tesla.getEfficiency()); //Will print 15.5
I have a class that has a variable of type Name.
public class Holder {
private Name name;
private int snumber;
The Name class has two strings called first and last that are assigned values by setter methods. I would like to send over the strings from the Name class to name in the Holder class, but I'm having trouble doing so. I think I've taken a step in the right direction by doing this
public class Holder {
private Name name;
private int snumber;
public void setName(){
name = new Name();
name.getFirst();
name.getLast();
}
but I can't say that I really know what the correct approach is. I also tried name.setFirst(getFirst) but that doesn't work. Any ideas would be appreciated.
The same way you would if the class wasn't nested.
Your setName() method should take a parameter (maybe 2, first and last) and then invoke the name.setFirstName(), name.setLastName() methods.
Right now, your setName() method isn't doing anything.
E.G:
public class Holder
{
private Name name;
private int snumber;
public Holder()
{
this.name = new Name();
}
public void setName(String firstName, String lastName)
{
this.name.setFirst(firstName);
this.name.setLAst(lastName);
}
}
Here is a good article explaining the relationship between Java inner and outer classes:
https://www.tutorialspoint.com/java/java_innerclasses.htm
class Outer_Demo {
// private variable of the outer class
private int num = 175;
// inner class
public class Inner_Demo {
public int getNum() {
System.out.println("This is the getnum method of the inner class");
return num;
}
}
}
public class My_class2 {
public static void main(String args[]) {
// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();
// Instantiating the inner class
Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();
System.out.println(inner.getNum());
}
}
Note that the example creates instances of both "Outer_Demo" AND "Inner_Demo (outer.new Inner_Demo();).
Ok, so I figured something out that works.
public class Holder {
private int snumber;
private Name name;
public void setName(Name n){
name=n;
}
public Name getName(){
return name;
}
I am a beginner in JAVA and I could use some help. So I have 3 classes : Client,BankAccount and Test. I need to add into a Client object the details from a BankAccount. This is the code:
public class Client {
private String name;
private String adress;
private BankAccount accounts[];
public Client(String name,String adress,BankAccount accounts){
this.name=name;
this.adress=adress;
this.accounts=accounts;
}
public class BankAccount {
private String numarCont;
private float suma;
public ContBancar(String accNumber,float sum){
this.accNumber=accNumber;
this.sum=sum;
}
public class Test {
public static void main(String[] args) {
Bankaccount b=new Bankaccount("f211s1",200);
Bankaccount b1=new Bankaccount("f23131EUR",5000);
System.out.println(b);
Client c=new Client("John","142VineYard",b);
System.out.println(c);
}
}
A client can have multiple accounts. The problem is that I don't know how can I add the details of object b into object c.
Use a List for your BankAccounts
public class Client {
private String name;
private String adress;
private List<BankAccount> accounts = new ArrayList<BankAccount>();
public Client(String name,String adress,BankAccount account){
this.name=name;
this.adress=adress;
this.accounts.add(account);
}
public void addBankAccount(BBankAccount account){
this.accounts.add(account);
}
}
This way it is a easier to add Accounts.
c.addBankAccount(b);
c.addBankAccount(b1);
Maybe it would help you to take a look at some basic Java tutorials.
It sounds like what you want is inheritance. Inheritance will allow you to use the methods of one class in another class as if it was the same object. The keyword for inheriting in Java is extends used like this:
Public class foo extends foobar
I am trying to access the private data member of inner class outside the outer class.
Please help me?
You don't - that's the whole point of it being private.
The inner class can expose the data via a property, of course:
public class Outer {
public class Inner {
private final String name;
public Inner(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}
public class Other {
public void foo() {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner("Foo");
// Can't access inner.name here...
System.out.println(inner.getName()); // But can call getName
}
}
... but if the inner class wants to keep it private, then you shouldn't try to access it.
Create public getter setter methods inside the inner class for private variables. Then create an object and call them to access private data. You can't directly access private data.
you cant access a private data. If ýou have other thoughts of accessing it use public getter method returning that private data.
you can access private data member using getter method ex
package pack;
import java.io.ObjectInputStream.GetField;
public class abc {
private int num = 2;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
class otherClass {
public static void main(String[] args) {
abc obj = new abc();
System.out.println(obj.getNum());
}
}