Variables for objects -- Java - java

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

Related

Call a different constructor depending on the static type of the instance created

I have a program where a class car implements two interfaces : rentable and buyable.
My class looks something like this:
Class Car implements IRentable, IBuyable{
private String name;
private float rentValue;
private float sellValue;
//rentable constructor
public Car(String name, float rentValue){
...
}
//buyable constructor
public Car(String name, float buyValue){
...
}
...
}
And the instantiation of the object would look something like this:
IRentable c1= new Car("name",700f);
IBuyable c2= New Car ("name",35_000f);
I was wondering if there is a way to call a specific constructor based on the static type of the object. For example, if I have the IRentable type:
IRentable c1= new Car("name",700f);
call the rentable constructor.
If I have the IBuyable type:
IBuyable c2= New Car ("name",35_000f);
call the buyable constructor.
This is not possible as different constructors need different method signatures.
You could have one constructur with a flag as third parameter:
IRentable c1= new Car("name",700f,true);
IBuyable c2= New Car ("name",35_000f,false);
I think for this case you should consider builder pattern or if you only need those two constructors then you could make the all args constructor private and create two static methods that would create you objects accordingly.
Use static methods, which can be named to clarify the difference. Make the constructor private.
class Car implements IRentable, IBuyable {
private String name;
private float rentValue;
private float buyValue;
public static IRentable rent(String name, float rentValue) {
return new Car(name, rentValue, Float.NaN);
}
public static IBuyable buy(String name, float buyValue) {
return new Car(name, Float.NaN, buyValue);
}
private Car(String name, float rentValue, float buyValue) {
...
}
...
}
They are used like this:
IRentable c1 = Car.rent("name", 700f);
IBuyable c2 = Car.buy("name", 35_000f);
You can't create more than 1 constructor with the same type signature(s). If a car is only suppose to be either Rentable or Buyable, you could create a single interface that both of the aforementioned interfaces extend like Costable (bad name i know).
interface Costable {
float amount();
}
Then compose the Car of a Costable object.
class Car implements Costable {
private final Costable;
public Car(Costable costable) {
this.costable = costable;
}
#Override
public float amount() {
return costable.amount();
}
}
Then you could extend Rentable/Buyable with your implementations. Here is an example with IRentable like you have above.
class IRentable implements Costable {
private final float amount;
public IRentable(float amount) {
this.amount = amount;
}
#Override
public float amount() {
return amount;
}
}
Costable rentable = new Car(new IRentable(1_000));

Java create array of classes within class from outside static class

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

Does a subclass inherit the private properties of its parent class, in java?

The book I am reading says I cant, but my program proves otherwise. For example the code below compiles well, even though i try to access the private properties of the parent class. Then I can freely print them. Can anyone tell me if the book is wrong, or am I doing something wrong?
class Asset
{
private int Id;
private String type;
public int getId()
{
return Id;
}
public String getType()
{
return type;
}
public void setId(int Id)
{
this.Id=Id;
}
public void setType(String type)
{
this.type=type;
}
public void printDescription()
{
System.out.println("Asset Id: "+Id);
System.out.println("Asst type: "+ type);
}
}
class BankAccount extends Asset
{
private String bankName;
private int accountNumber;
private float balance;
public String getBankName()
{
return bankName;
}
public int getAccountNumber()
{
return accountNumber;
}
public float getBalance()
{
return balance;
}
public void setBankName(String bankName)
{
this.bankName=bankName;
}
public void setAccountNumber(int accountNumber)
{
this.accountNumber=accountNumber;
}
public void setBalance(float balance)
{
this.balance=balance;
}
public void printDescriptionnn()
{
System.out.println("The Bank name is: "+ bankName);
System.out.println("Account number: "+ accountNumber);
System.out.println("Your balance is: "+ balance);
}
}
public class AssetTest
{
public static void main(String[] args)
{
BankAccount llogari= new BankAccount();
Scanner input = new Scanner(System.in);
Scanner sinput= new Scanner(System.in);
System.out.print("Type the ID of your asset: ");
llogari.setId(input.nextInt());
System.out.print("Type the type of your asset: ");
llogari.setType(sinput.nextLine());
System.out.print("Give the bank name: ");
llogari.setBankName(sinput.nextLine());
System.out.print("Type the Account Number: ");
llogari.setAccountNumber(input.nextInt());
System.out.print("Type your balance: ");
llogari.setBalance(input.nextFloat());
llogari.printDescription();
llogari.printDescriptionnn();
}
}`
You can access them through public or protected getters but you can't access the private properties directly. In your example, you're using the public setters to modify the property. You can access them through public method !
So to answer you question, private members are not inherited by subclasses. Alternatively, you can have protected members that are inherited by subclasses.
EDIT
From Java Language Specificiation
Members of a class that are declared private are not inherited by subclasses of that class.
Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared.
Because you're not directly modifying the parent class's elements. You're calling public functions that modify the private elements, which is completely valid.
A subclass does not have direct access to the private members of a super class. It only has direct access to the public and protected members.
In this context, direct access means: super.member
If the super class implements protected or public accessor or mutator methods, then you may be able to indirectly access them. Indirect access would look something like: super.getMember() or super.doSomething().
Any subclass does not have permission to direct access of the private members of a super class. It can access to the public and protected members.

How to access private data member outside the class?

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

Simulating a Car (Java)

I'm working on a project to simulate a car. The requirements are to demonstrate the operation of a car by filling it with fuel and then run the car until it has no more
fuel. Simulate the process of filling and running the car at different speeds. As the car is running, periodically print out the car’s current mileage, amount of fuel and speed.
I wrote some other classes to hold some methods that I will use to calculate the fuel, speed, and mileage. I'm just having a little trouble on how I should go about making it work like an actual car would, any help would be appreciated.
public class FuelGauge {
protected double fuel;
public FuelGauge()
{
fuel = 0.0;
}
public double getFuel()
{
return fuel;
}
public void setFuel(double fuel)
{
this.fuel = fuel;
}
public void fuelUp()
{
if(fuel<18)
fuel++;
}
public void fuelDown()
{
if(fuel>0)
fuel--;
}
}
public class Odometer extends FuelGauge {
private int mileage, mpg;
private int economy;
public int getMileage()
{
return mileage;
}
public void setMileage(int mileage)
{
this.mileage = mileage;
}
public int getMpg()
{
return mpg;
}
public void setMpg(int mpg)
{
this.mpg = mpg;
}
public void mileUp()
{
if(mileage<999999)
mileage++;
}
public void mileReset()
{
if(mileage>999999)
mileage = 0;
}
public void decreaseFuel(int fuel)
{
if(mileage == mpg)
fuelDown();
}
public int getEconomy()
{
return (int) (mileage/fuel);
}
public void setEconomy(int economy)
{
this.economy = economy;
}
}
public class Car extends Odometer{
private String name;
private int speed;
public Car()
{
name = "Car";
getMileage();
getMpg();
getEconomy();
getFuel();
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getSpeed()
{
return speed;
}
public void setSpeed(int speed)
{
this.speed = speed;
}
public void increaseSpeed()
{
if(speed<=120)
speed++;
}
public void decreaseSpeed()
{
if(speed>0)
speed--;
}
}
I would more recommend the contains vs isa relationship for the components of your car.
class FuelGauge { ... }
class Odometer { ...}
class Vehicle { ... }
class Car extends Vehicle
{
private FuelGauge fuelGauge = new FuelGauge();
private Odometer odometer = new Odometer();
...
}
Well, here are some suggestions:
Start the car.
Pull out from your driveway; if that's not needed, start driving
If you plan to drive at a fixed speed, you can calculate how long the ride would take in advantage, and just use a loop to update the distance and fuel; otherwise, you can store a set of speeds in an array, use a loop, and pass the variable speeds on each iteration (this might be a little hard to calculate how much fuel is left)
Hope that helps the inspiration running.
Here is the design of your car simulator application :
Identify Car class which will have odometer reading, current fuel inside tank etc as the instance variables.
Write a thread which continuously run with some sleep time of 100 millis or so for every iteration and inside the thread's run method you deal with the logic of incresing the odometer reading and decreasing the fuel in some proportion. make sure that your thread will run till the fuel in tank is greater than 0. if in case you can raise an event or alarm just in cse the fuel is below a certain constant.
Write the main class to initiate the class with full tank fuel (may be 40 ltrs a constant) and odometer reading to 0 and then start the thread.
Hope this is helpful.
-KishoreMadina

Categories