Here is my field.java class. Ive got the public Field(String name, int number) defined here.
public class Field
{
String name;
int number;
public Field(String name, int number){
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public int getNumber() {
return number;
}
#Override
public String toString() {
return "Field{" + "name=" + name + ", number=" + number + '}';
}
}
Here is my Player.java class, Im getting an error on my Field currentField = new Field(); - it says that my Field is not defined as a constructor in my Field.java class
public class Player
{
private String name;
private int pos;
Field currentField = new Field();
public Player()
{
}
}
Anyone got a suggestion on why Im throwing errors?
You have provided a parameterized constructor in your class
public Field(String name, int number){
this.name = name;
this.number = number;
}
And hence no default (no-arg) constructor is provided when you define a parametrized constructor.
So when you are trying to create an instance using Field currentField = new Field();, it cannot compile since there is no matching constructor.
Solutions you can try:
1.
Add a no-arg constructor to your class :
public Field()
{
}
Or
2.
While creating an instance, pass values to constrcutor :
Field currentField = new Field("abc", 123);
Yes because your class receiving two arguments name and number and you are trying to create instance of it without passing them.
Either you can pass them
Field currentField = new Field("test", 1); // for ex :
or create a default no arg constructor to your Field class.
/** default no arg constructor **/
public Field(){
// TODO : when there is no param
}
Field currentField = new Field();
You are not passing any arguments to the constructor. You will either need to provide a name and number as parameters, or define a default constructor :
public Field(String name, int number){
this.name = name;
this.number = number;
}
Field currentField = new Field("fieldName", 1);
or
public Field(){
this.name = "";
this.number = 0;
}
Field currentField = new Field();
In every Java class there is a default constructor, if you add any other constructor it will override the default constructor. So to make your code work you have to add no argument constructor.
public Field(){
}
Related
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
This question already has answers here:
Java error: Implicit super constructor is undefined for default constructor
(12 answers)
Closed 8 years ago.
I'm trying to extend my Vehicle class to a HumanPowered class -- Has a field for calories per hour. This is my first time trying to extend a class so I'm a bit confused here.
class Vehicle
{
String description;
String idNumber;
int numWheels;
public Vehicle(String aDescription, String aIdNumber, int aNumWheels)
{
description = aDescription;
idNumber = aIdNumber;
numWheels = aNumWheels;
}
void setDescription (String aDescription)
{
description = aDescription;
}
void setIdNumber (String aIdNumber)
{
idNumber = aIdNumber;
}
void setNumWheels (int aNumWheels)
{
numWheels = aNumWheels;
}
public String getDescription()
{
return description;
}
public String getIdNumber()
{
return idNumber;
}
public int getNumWheels()
{
return numWheels;
}
public String toString()
{
String result= String.format("ID: %s Description: %s Wheels: %d",idNumber,description,numWheels);
return result;
}
}
class humanPowered extends Vehicle
{
int calories;
public humanPowered(String aDescription, String aIdNumber, int aNumWheels, int aCalories) //Error here
{
description = aDescription;
idNumber = aIdNumber;
numWheels = aNumWheels;
calories = aCalories;
}
void setCalories (int aCalories)
{
calories = aCalories;
}
public int getCalories()
{
return calories;
}
public String toString()
{
String result= String.format("ID: %s Description: %s Wheels: %d Calories per Hour: %d",idNumber,description,numWheels, calories);
return result;
}
}
I'm getting an error marked above on my constructor for my humanPowered class saying "Implicit super constructor Vehicle() is undefined. Must explicitly invoke another constructor." I can't figure out where I'm going wrong here. Thanks for any and all help!
Vehicle don't have default constructor hence you have to call its constructor form humanPowered class passing required arguments at the first line of its constructor.
public humanPowered(String aDescription, String aIdNumber, int aNumWheels, int aCalories)
{
super(aDescription,aIdNumber,aNumWheels);
...//other code
}
Points to remember:
Every class have default constructor that is no-argument constructor
If class creates a constructor passing arguments then by default constructor is not created
Each constructor by default calls default constructor of its super-class
can i get Field (Variable/Property) name using method in Java using Reflection? I am explaining my scenario in following code.
for example, i have one class
class MyBean
{
String name;
String Name;
public String getName() {
return Name;
}
public void setName(String name) {
this.Name = name;
}
}
now i want field "Name" by using java.lang.reflect.Method "getName()"...can i get it?
i want function something like this..
public String getFieldName(Method method)
{
String fieldName=null;
// code for finding field/variable/property name using method
return fieldName;
}
please help me, if possible...thanks in advance
If you are naming your fields by JavaBeans convention, this should do all the thing:
public String getFieldName(Method method) {
return method.getName().substring(3).toLowerCase();
}
So the getName() or setName() should return "name"
This works, but your class is not cleanly defined.
Fields should be named using camelCase notation starting with a lower char:
class Info
{
public String name1;
private String name2;
}
Now you have an object info:
Info info;
Then you want to get the value of name1:
Here is a full Test case showing all:
public class InfoTest extends TestCase{
public static class Info {
private String name1;
public String name2;
protected String name3;
String name4;
/**
* Default constructor.
*/
public Info() {
name1 = "name1Value";
name2 = "name2Value";
name3 = "name3Value";
name4 = "name4Value";
}
}
public void testReflection() throws IllegalArgumentException, IllegalAccessException {
Info info1 = new Info();
Field[] infoFields = info1.getClass().getDeclaredFields();
for (int i = 0; i < infoFields.length; i++) {
Field fieldName = infoFields[i];
System.out.println("the name of the field " + i + ":" + fieldName.getName());
fieldName.setAccessible(true);
Object info1ValObj = infoFields[0].get(info1);
System.out.println("the value of the field: " + info1ValObj.toString());
}
}
}
The output then is:
the name of the field 0:name1
the value of the field: name1Value
the name of the field 1:name2
the value of the field: name1Value
the name of the field 2:name3
the value of the field: name1Value
the name of the field 3:name4
the value of the field: name1Value
Do you mean?
public String getFieldName(Method method) {
return method.getName().substring(3);
}
BTW: field names should be in camcelCase not TitleCase
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
}
}
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 ;-)