Getting Rid of an Object's Reference - java

I want to get rid of each object's reference in my tester class, but I'm getting errors. The methods I'm using were given to me in notes but not sure if they're correct.
Any help will be appreciated :)
Here's my code:
public class Bicycle {
// Instance Variables
private String name; // Owner's name
private int age; // Owner's age
private char gender; // Owner's gender
private static int instanceCounter = 0;
// Default Constructor - doesn't take in values
public Bicycle() {
this("Not Given", 0, 'U');
instanceCounter++;
}
// Parameter constructor
public Bicycle(String name, int age, char gender) {
this.name = name;
this.age = age;
this.gender = gender;
instanceCounter++;
}
// Getter and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public int countInstances(){
return instanceCounter;
}
}
Tester:
public class BicycleTester {
public static void main(String args[]){
// Instance one
Bicycle bicycle1 = new Bicycle(null, 0, 'U');
bicycle1.setName("John");
System.out.println("Name: " +bicycle1.getName());
bicycle1.setAge(18);
System.out.println("Age: " +bicycle1.getAge());
bicycle1.setGender('M');
System.out.println("Gender: " +bicycle1.getGender());
System.out.println("");
// Instance two
Bicycle bicycle2 = new Bicycle(null, 0, 'U');
bicycle2.setName("Mary");
System.out.println("Name: " +bicycle2.getName());
bicycle2.setAge(23);
System.out.println("Age: " +bicycle2.getAge());
bicycle2.setGender('F');
System.out.println("Gender: " +bicycle2.getGender());
System.out.println("");
// Instance three
Bicycle bicycle3 = new Bicycle(null, 0, 'U');
bicycle3.setName("Billy");
System.out.println("Name: " +bicycle3.getName());
bicycle3.setAge(15);
System.out.println("Age: " +bicycle3.getAge());
bicycle3.setGender('M');
System.out.println("Gender: " +bicycle3.getGender());
System.out.println("");
// Three ways to get rid of object's reference
void go() {
Life bicycle1 = new Life();
}
Life bicycle2 = new Life();
bicycle2 = new Life();
Life bicycle3 = new Life();
bicycle3 = null;
}
}

Ok Ma'am Lets go over the basics again.
We will start with the difference between an Object AKA instance and a reference.
Life bicycle2 = new Life();
Here, bicycle2 is a reference it will be on the Stack. The reference points to the instancecreated by the call to new Life(). The instance will be on the Heap
You can't get rid of an Object's reference. You can get rid of an instance.
There is only one wayof doing that.
Set the reference pointing to the instance to null or to some other instance
example : Life bicycle2 = new Life();
bicycle2 = null;// the instance created above will be eligible for GC
or you could also do :
Life bicycle2 = new Life();
bicycle2 = new Life();// the life instance created above will be discarded.
Note that : a reference is scope dependent once it goes out of scope, it will not be accessible. I don't think you arre talking about that here.

In the case of your no-argument constructor, you're incrementing instanceCounter twice - once when you call the other constructor with parameters, and once when that completes in the no-args constructor as well.
You're also not decrementing the count anywhere, so if you're using that as a means to keep track of how many instances of your class are in memory, your count will be off.

Related

Java if/else statement

I am working on my final project in a computer class and am trying to implement a basic if/else statement in a nested class but it is only opting to use the else case.
import java.util.Scanner;
public class CollegeApplication {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//create object by default constructor
College c1 = new College();
//create object by overloaded constructor
College c2 = new College("Frostburg", "Frostburg", "MD", 5142);
College c3 = new College("UMBC", "Baltimore", "MD", 14000);
//set the information of object 1
c1.setName("Full Sail");
c1.setCity("Winter Park");
c1.setState("FL");
c1.setStudent_Body(19285);
System.out.println("Enter your states two-letter abbreviation");
String user_State = scan.nextLine();
c1.printCollege();
System.out.println();
c2.printCollege();
System.out.println();
c3.printCollege();
}
}
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
import java.util.Scanner;
public class College {
// private data members
private String name;
private String city;
private String state;
private int student_Body;
private String tuition;
private String user_State;
// default constructor which set the data member to default value
public College() {
this.name = "";
this.city = "";
this.state = "";
this.student_Body = 0;
this.tuition = "";
this.user_State = "";
}
// parameterized constructor
public College(String name, String city, String state, int student_Body) {
super();
this.name = name;
this.city = city;
this.state = state;
this.student_Body = student_Body;
}
// getter and setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getStudent_Body() {
return student_Body;
}
public void setStudent_Body(int student_Body) {
this.student_Body = student_Body;
}
// print college data
public void printCollege() {
System.out.println("Name of College: " + name);
System.out.println("City of Collge: " + city);
System.out.println("State of Collge: " + state);
System.out.println("Student Body Count: " + student_Body);
this.user_State = user_State;
if (state.equals(user_State)) {
this.tuition = "Eligible";
}
else {
this.tuition = "Ineligible";
}
System.out.println("In-State Tuition: " + tuition);
}
}
If anyone could help id be greatly appreciative in knowing how to alter the if statement to not only print ineligible
This question does not contain a question but I see the problem area.
Ask yourself why your College has both a state and a user_State. Why would this class have an aspect of itself be a user_State? There isn't even a getter and setter for it (as there shouldn't be).
public void printCollege() {
this.user_State = user_State;
if (state.equals(user_State)) {
this.tuition = "Eligible";
}
else {
this.tuition = "Ineligible";
}
System.out.println("In-State Tuition: " + tuition);
}
This function takes no input and gives no output, but has side-effects of printing something and modifying fields.
The only other time user_State is referenced in College is when it's set to the empty string.
this.user_State = "";
And that's only when a College object is constructed with the default constructor. If a College object is made using the argument constructor, user_State remains null.
Anyway, this method begins by setting this empty string (or null) to itself:
this.user_State = user_State;
So it's just going to be the empty string (or null).
Next it compares the strings state with the empty string or null in user_State.
if (state.equals(user_State)) {
state is not equal to the empty string nor null in any of your test cases, so it continues to the else clause:
else {
this.tuition = "Ineligible";
}
What you probably intend is for printCollege() to take the user_State variable you asked the user for. In which case it does not take 0 arguments, it takes 1 string argument.
public void printCollege(String userState) {
if (state.equals(userState)) {
this.tuition = "Eligible";
}
else {
this.tuition = "Ineligible";
}
System.out.println("In-State Tuition: " + tuition);
}
and the invocations of printCollege(String userState) should be done as appropriate, with the input you received from the user.
Please follow Java naming conventions in the future, something like user_State should just be userState.
there is no setter method for user_State instance variable
no parameter provided for initialization of user_State instance variable
so if condition fails as it considers user_State variable as instance variable it will always be "" in case of default constructor and "null" in case of parameterized constructor
either
provide parameter to printCollege() method according to #PatricChen
or
remove the statement this.user_State = user_State from
printCollege() and provide setter method for user_State variable and
a user_State parameter to parameterized constructor of College class

How would I add an object with an int and a string value to an array in Java

So far for the class I have:
public class Candidate
{
// instance variables
private int numVotes;
private String name;
// Constructor for objects of class Candidate
public Candidate(String name, int numVotes)
{
// initialize instance variables
this.name = name;
this.numVotes = numVotes;
}
public String getName()
{
return name;
}
public int getVotes()
{
return numVotes;
}
public void setVotes(int n)
{
numVotes = n;
}
public void setName(String n)
{
name = n;
}
public String toString()
{
return name + " received " + numVotes + " votes.";
}
}
I have a tester class where I have an array that I want to add the objects to. The tester class so far is:
public class ElectionTesterV1
{
Candidate Candidate[] = new Candidate[5];
}
So far I have tried
Candidate[0] = ("John Smith",5,000);
but I get lost of errors illegal start type and identifier needed. How would I add an object with the same format with a name and then a number into the array. I'm supposed to be using an array, not an arraylist
Your array is Candidate[], so therefore it needs to hold instances of Candidate. The class Candidate may be instantiated with a String and and int (per the constructor).
Note: I changed the array name to candidates (plural) to help distinguish the usage.
You can add to the array by:
// create the array
Candidate[] candidates = new Candidate[5];
// add the first person
candidates[0] = new Candidate("John Smith", 5000);
So the test class might look like:
public class ElectionTesterV1
{
// array of Candidate objects called candidates
Candidate[] candidates = new Candidate[5];
candidates[0] = new Candidate("John Smith", 5000);
candidates[1] = new Candidate("Mary Sue", 8765);
...
}

Setters, why won't this work?

I've been toying for hours, changing static, private, public etcetera :) But it still won't work. If I change static at one place, I get an error at another place etc.
I have a class called person. I've used NON-static Setters because the Person() constructor is also non-static.
public class Person {
private String name;
private String lastname;
private String nickname;
Person() {
this.name = "";
this.lastname = "";
this.nickname = "";
}
public void setName(String name) {
this.name = name;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
}
Then I have a file with my main method, and different methods for interacting with the user.This method is also static because it calls that methods that take the userInput which is using the Scanner class.
public class Interaction {
public static void takeName() {
String name;
String lastname;
String nickname;
System.out.println("What is your firstname:");
name = userInput(); // calls method with Scanner class
System.out.println("What is your lastname:");
lastname = userInput(); // calls method with Scanner class
System.out.println("What is your nickname:");
nickname = userInput();
person.setName(name);
person.setLastname(lastname);
person.setNickname(nickname);
}
//editor: missing closing bracket
What I've tried:
I've tried to dat Person.person.setname(name);
Declare the String in the public class Interaction, and then pass the String using this.name and call the method from the public class Interaction
tried to change static, private etc. etc.
Delete the constructor class Person() in Person class.
What am I missing here?
EDIT: I'VE ADDED SOME MORE INFO as you requested :)
My new Person object will be declared if it passes an if statement.
IF there is a place available then a new person will be created and added to this place.
public class Theater {
void reservationSystem () {
if (availability > 0) {
for (int i = 0; i < freespaces.length; i++) {
if (freespaces[i].person == null) {
freespaces[i].person = new Person();
break;
}
}
} else {
System.out.println("No tickets for you today :) ");
}
}
//editor: missing closing bracket
So my way of thinking is:
I fill a constructor with the data from the Userinput() using the Scanner class;
and THEN I create the new Person object so it has that data!
When I create a new Person in the reservation system, then the data in the constructor will be filled with data AGAIN but now with new data :)
If you need any more information please let me know :)
The first thing to note is that your Person constructor is a little useless, you can rewrite Person as such:
public class Person {
private String name = "";
private String lastname = "";
private String nickname = "";
public void setName(String name) {
this.name = name;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
}
Now onto your Interaction class. This needs to by public rather than Public but I assume that's a typo.
You need to have an instance of Person to call your setters on as they are instance methods. You need to somewhere call new Person().
The easiest way of writing your takeName() method is by creating a Person in the method and returning the instance:
public class Interaction {
public static Person takeName() {
final Person person = new Person();
System.out.println("What is your firstname:");
person.setName(userInput());
System.out.println("What is your lastname:");
person.setLastname(userInput());
System.out.println("What is your nickname:");
person.setNickname(userInput());
return person;
}
}
Your 'takeName()` function should update a single instance of the Person class.
One approach is to create the Person externally and pass it to the function:
Public class Interaction {
public static void takeName(Person person) {
String name;
String lastname;
String nickname;
System.out.println("What is your firstname:");
name = userInput(); // calls method with Scanner class
System.out.println("What is your lastname:");
lastname = userInput(); // calls method with Scanner class
System.out.println("What is your nickname:");
nickname = userInput();
person.setName(name);
person.setLastname(lastname);
person.setNickname(nickname);
}
}
But I think it would be more intuitive to create the person instance inside the function and return it:
Public class Interaction {
public static Person takeName() {
String name;
String lastname;
String nickname;
Person person = new Person();
System.out.println("What is your firstname:");
name = userInput(); // calls method with Scanner class
System.out.println("What is your lastname:");
lastname = userInput(); // calls method with Scanner class
System.out.println("What is your nickname:");
nickname = userInput();
person.setName(name);
person.setLastname(lastname);
person.setNickname(nickname);
return person;
}
}
Because this is not valid syntax: Person.person.setname(name);
What this would mean in this context is:
get class named Person
get static field of Person class named person
find and invoke instance methid setname with argument name
But your Person class - appropriately - does not have a static field named person...
The root cause of your issues is most likely not being entirely familiar with the concept of classes, instances, and in connection, the meaning of static and instance members and methods...
Static always means the referenced part is connected with the class.
Whereas an instance variable or method (e.g. everything non-static) is connected to the instances of said classes.

Use of "this" keyword in java [duplicate]

This question already has answers here:
What is the meaning of "this" in Java?
(22 answers)
Closed 7 years ago.
I was studying method overriding in Java when ai came across the this keyword. After searching much about this on the Internet and other sources, I concluded that thethis keyword is used when the name of an instance variables is same to the constructor function
parameters. Am I right or wrong?
this is an alias or a name for the current instance inside the instance. It is useful for disambiguating instance variables from locals (including parameters), but it can be used by itself to simply refer to member variables and methods, invoke other constructor overloads, or simply to refer to the instance. Some examples of applicable uses (not exhaustive):
class Foo
{
private int bar;
public Foo() {
this(42); // invoke parameterized constructor
}
public Foo(int bar) {
this.bar = bar; // disambiguate
}
public void frob() {
this.baz(); // used "just because"
}
private void baz() {
System.out.println("whatever");
}
}
this keyword can be used for (It cannot be used with static methods):
To get reference of an object through which that method is called within it(instance method).
To avoid field shadowed by a method or constructor parameter.
To invoke constructor of same class.
In case of method overridden, this is used to invoke method of current class.
To make reference to an inner class. e.g ClassName.this
To create an object of inner class e.g enclosingObjectReference.new EnclosedClass
You are right, but this is only a usage scenario, not a definition. The this keyword refers to the "current object". It is mostly used so that an object can pass itself as a parameter to a method of another object.
So, for example, if there is an object called Person, and an object called PersonSaver, and you invoke Person.SaveYourself(), then Person might just do the following: PersonSaver.Save( this );
Now, it just so happens that this can also be used to disambiguate between instance data and parameters to the constructor or to methods, if they happen to be identical.
this keyword have following uses
1.used to refer current class instance variable
class Student{
int id;
String name;
student(int id,String name){
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}
}
here parameter and instance variable are same that is why we are using this
2.used to invoke current class constructor
class Student{
int id;
String name;
Student (){System.out.println("default constructor is invoked");}
Student(int id,String name){
this ();//it is used to invoked current class constructor.
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student e1 = new Student(111,"karan");
Student e2 = new Student(222,"Aryan");
e1.display();
e2.display();
}
}
3.this keyword can be used to invoke current class method (implicitly)
4.this can be passed argument in the method call
5.this can be passed argument in the constructor call
6.this can also be used to return the current class instance
This refers current object. If you have class with variables int A and a method xyz part of the class has int A, just to differentiate which 'A' you are referring, you will use this.A. This is one example case only.
public class Test
{
int a;
public void testMethod(int a)
{
this.a = a;
//Here this.a is variable 'a' of this instance. parameter 'a' is parameter.
}
}
Generally the usage of 'this' is reserved for instance variables and methods, not class methods ...
"class methods cannot use the this keyword as there is no instance for
this to refer to..."
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Here's a trivial example ...
public class Person {
private String name;
private int age;
private double weight;
private String height;
private String gender;
private String race;
public void setName( String name ) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setAge( int age) {
this.age = age;
}
public int getAge(){
return this.age;
}
public void setWeight( double weight) {
this.weight = weight;
}
public double getWeight() {
return this.weight;
}
public void setHeight( String height ) {
this.height = height;
}
public String getHeight() {
return this.height;
}
public void setGender( String gender) {
this.gender = gender;
}
public String getGender() {
return this.gender;
}
public void setRace( String race) {
this.race = race;
}
public String getRace() {
return this.race;
}
public void displayPerson() {
System.out.println( "This persons name is :" + this.getName() );
System.out.println( "This persons age is :" + this.getAge() );
System.out.println( "This persons weight is :" + this.getWeight() );
System.out.println( "This persons height is :" + this.getHeight() );
System.out.println( "This persons Gender is :" + this.getGender() );
System.out.println( "This persons race is :" + this.getRace() );
}
}
And for an instance of a person ....
public class PersonTest {
public static void main( String... args ) {
Person me = new Person();
me.setName( "My Name" );
me.setAge( 42 );
me.setWeight( 185.00 );
me.setHeight( "6'0" );
me.setGender( "Male" );
me.setRace( "Caucasian" );
me.displayPerson();
}
}
In case of member variable and local variable name conflict, this key word can be used to refer member variable like,
public Loan(String type, double interest){
this.type = type;
this.interest = interest;
}
if you have knowladge about c,c++ or pointers, in that language this is a pointer that points object itself. In java everything is reference. So it is reference to itself in java. One of the needs of this keyword is that:
Think that this is your class
public class MyClass
{
public int myVar;
public int myMethod(int myVar)
{
this.myVar = myVar; // fields is set by parameter
}
}
If there is not this keyword you it is confused that this is paramter or class field.When you use this.myVar it refers field of this object.
I would like to modify your language. The this keyword is used when you need to use class global variable in the constructors.
public class demo{
String name;
public void setName(String name){
this.name = name; //This should be first statement of method.
}
}
this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
One more thing that should be in mind is that this keyword might be the first statement of your method.
This is used in java. We can use in inheritance & also use in method overloading & method overriding. Because the actual parameter or instance variable name has same name then we can used this keyword complsary . But some times this is not same as when we can not use this keyword complsary.....
Eg:- class super
{
int x;
super(int x)
{
this.x=x
}
}

Java, I need help instantiating an object

Hello I'm new to Java. I'm trying to create a object and pass name through it. I don't have a clue what I'm doing wrong?.
public class Employee
{
private String name, number;
private String date;
public Employee()
{
name= "";
number = "";
date = "";
}
public Employee(String name, String number, String date)
{
setName(name);
setNumber(number);
setDate(date);
}
public void setName(String n)
{
name = n;
}
public void setNumber(String n)
{
number = n;
// you can check the format here for correctness
}
public void setDate(String d)
{
date = d;
}
public String getName()
{
return name;
}
public String getNumber()
{
return number;
}
public String getDate()
{
return date;
}
}
import java.util.Scanner;
public class TeamLeadDemo
{
public static void main(String[] args)
{
String name;
// create scanner object
Scanner keyboard = new Scanner(System.in);
// inputting data
System.out.println("Enter Name:");
name = keyboard.nextLine();
// instantiating object, HERE IS THE PROBLEM
Employee thename = new Employee(name);
// outputting data
System.out.println("Employee Name:"+thename.getName());
System.out.println("Employee Details:\n" + thename);
}
}// Function definition
What should i do??
Hey fellow newbie programmer!
Take a look at how you initialize your object:
Employee thename = new Employee(name);
Since you only give it the String name as a parameter, Java cannot initialize your Employee object because it does not have a single argument constructor!
Here are your constructors method signatures:
public Employee()
public Employee(String name, String number, String date)
One takes no arguments, and the other takes 3 arguments.
If you look at the way you initialize it, you only pass 1 argument!
You would need to create a new Constructor that has a single argument in order for your code to work. Or easier yet, you could just pass in "", "" for your number and date string values.
More experienced programmers please do not hesitate to correct my programming semantics if they are wrong. I feel like I'm using words that I do not fully understand.
You need a constructor that receives only the name that you are passing:
public Employee(String name) {
this.name = name;
this.number = "";
this.date = "";
}
Currently you only have one default constructor and one that receives all three properties.
Your Employee class has two constructors: one taking zero arguments and one taking three arguments. Yet you're attempting to construct it with one argument. That wouldn't compile.
There are two possible solutions:
Add another constructor taking one argument.
public Employee(String name) {
this.name = name;
}
Use the constructor taking three arguments and pass null through.
Employee employee = new Employee(name, null, null);
Unrelated to the concrete problem, setting values to empty strings in the default constructor and calling the setters in the second constructors is not a nice practice. In the first, just do nothing, keep them default null. In the second constructor, you should prefer setting the property directly instead of calling the setter.
You need to pass in the number and date to the constructor as well. Try:
Employee thename = new Employee(name, "", "");
Employee thename = new Employee(name);
You have no constructor that takes only one String
If you have some very very strong reasons not to use Employee thename = new Employee(name, "", "");, you may try "varargs"
As :
public class Employee {
String fname="";
String lname="";
public Emp(String... attrs) {
if ( attrs.length > 1 ) {
fname = attrs[0];
lname = attrs[1];
}else if(attrs.length == 1) {
fname = attrs[0];
}
}
public String toString() {
return fname + " " + lname;
}
public static void main(String[] args){
Employee e1 = new Employee ("Test");
Employee e2 = new Employee ("Test" ,"case");
System.out.println(e1);
System.out.println(e2);
}
}
Caution : this is just to answer your question- Think before using in real world situations. Not from design/ best approach perspective. But it is different and caters to your question though ;-)

Categories