Passing in parameters for super and subclasses? - java

The values I am supposed to pass in:
Name and family should be saved for all instruments
We need to specify whether a strings instrument uses a bow
When I run my code it gives me the error: "constructor Strings in class Strings cannot be applied to given types;"
public class InstrumentTester
{
public static void main(String[] args)
{
/**
* Don't Change This Tester Class!
*
* When you are finished, this should run without error.
*/
Wind tuba = new Wind("Tuba", "Brass", false);
Wind clarinet = new Wind("Clarinet", "Woodwind", true);
Strings violin = new Strings("Violin", true);
Strings harp = new Strings("Harp", false);
System.out.println(tuba);
System.out.println(clarinet);
System.out.println(violin);
System.out.println(harp);
}
}
public class Instrument
{
private String name;
private String family;
public Instrument(String name, String family)
{
this.name = name;
this.family = family;
}
public String getName()
{
return name;
}
public String getFamily()
{
return family;
}
public void setName(String name)
{
this.name = name;
}
public void setFamily(String family)
{
this.family = family;
}
}
public class Strings extends Instrument
{
private boolean useBow;
public Strings(String name, String family, boolean useBow)
{
super(name, family);
this.useBow = useBow;
}
public boolean getUseBow()
{
return useBow;
}
public void setUseBow(boolean useBow)
{
this.useBow = useBow;
}
}
How do I pass in the parameter family if it doesn't take it?

Strings violin = new Strings("Violin", true);
Strings harp = new Strings("Harp", false);
The violin and harp don't get passed a family name when they're created, so the Strings constructor mustn't expect one as an argument.
public Strings(String name, boolean useBow)
What do you pass to super(), then? If all strings belong to the same family then you can hard code the value. Perhaps just "String":
public Strings(String name, boolean useBow)
{
super(name, "String");
this.useBow = useBow;
}

you define strings as one single constructor
public Strings(String name, String family, boolean useBow)
but you try to use it as a different parameters:
Strings violin = new Strings("Violin", true);
either you need to define a second constructor or use the one you created

How do I pass in the parameter family if it doesn't take it?
This sounds like as if you are passing in the family but the class doesn't take it. But the truth is, your class is taking an extra family parameter that is not passed.
Given the comments at the start of main, my interpretation is that you are supposed to give all Strings a family of "Strings". As you can see from the usage in Main, only 2 arguments are passed to the constructor, which means the Strings constructor is not supposed to accept a family parameter.
Therefore, the constructor should be like this:
public Strings(String name, boolean useBow)
{
super(name, "Strings"); // note that I replaced family with "Strings"
this.useBow = useBow;
}

Related

Object to string delimited format

I have set of objects of different types.
Ex : Employee emp, adress adr
These two classes have list of properties
public class Employee{
private Stringname;
private int age;
}
public class Adress {
private String HouseNo;
private string Street;
private string pin;
}
Each attribute is assigned with some 2 character value
Name (NA), age (AG), HouseNo(HN),Street(ST), pin(PN)
I need to construct a string with these data and delimit with a %
Output:
NA%Vidhya%AG%30%HN%80%ST%1st cross%PN%100100
Each class knows it own data best so I would let each class be responsible for generating the string. As I understand it the two char codes for each field are unique for each class and member and only used when generating the string so only the class would need them.
interface AttributeDescription {
String generateDescription();
}
public class Employee implements AttributeDescription {
//members...
public String generateDescription() {
return String.format(“NA%%%s%%AG%%%d”, name, age)
}
Then simply call this method for all objects implementing the interface.
AttributeDescription object = ...
String attr = object.generateDescription();
I don't think it can be generalized more than this given the requirements.
Update
It might be better to have a builder class for building the string to get a more unified behavior between classes. Here is an example
public class AttributeBuilder {
private builder = new StringBuilder();
public String getAttribute() {
return builder.toString();
}
public void add(String code, String value) {
if (value == null) {
return;
}
builder.append(code);
builder.append(‘%’);
builder.append(value);
builder.append(‘%’);
}
}
And then you would also have to implement add(...) methods for other data types in a similar fashion. The builder could then be used like
public String generateDescription() {
AttributeBuilder builder = new AttributeBuilder();
builder.add(“NA”, name);
builder.add(“AG”, age);
return builder.getAttribute();
}

java dynamically call methods

I'm trying to figure out how to dynamically call a method. I have a string that describes the method name, but I'm not sure how to do it. I thought this could be done with reflection, but haven't had any success. Example
set.add(vehicleConfiguration.getVehicleYear.getName());
set.add(vehicleConfiguration.getVehicleMake().getName());
set.add(vehicleConfiguration.getVehicleModel().getName());
You'll notice all the method calls are the same with the exception of the getVehicleYear, etc
I have a string that describes the method names, just not sure how to use it.
I got as far as this with reflection, but failed.
set.add(Class.forName("VehicleConfiguration").getMethod("vehicleMake", null).getName());
Thanks in advance.
The class you are looking for is Method. Please read the appropriate javadoc carefully.
You can get a method with, for example
// assumign `getVehicleMake` is the name of the method and it accepts no parameters
Method method = VehicleConfiguration.class.getMethod("getVehicleMake");
// VehicleConfiguration.class can be replaced by
// Class.forName("VehicleConfiguration")
// if VehicleConfiguration is the fully qualified, ie. with packages, name of the class
// other you need Class.forName("com.yourpackage.VehicleConfiguration")
You then need to invoke() this method on an instance of your class.
VehicleConfiguration instance = new VehicleConfiguration();
Object returnObject = method.invoke(instance); // assuming no parameters
To then call getName(), you need to cast the returned object to the type that has the method. Assuming getMake() is a method of the type VehicleMake, call it like this
((VehicleMake)returnObject).getMake();
You have to use actual method name: getVehicleMake, not vehicleMake.
Additionally, if you're using this as anything other than an exercise, don't roll your own. Use Commons BeanUtils or Spring's BeanWrapper.
Expanding on my comment, As all the methods you showed have a getName() method, let's create a simple class which defines this:
class Nameable
{
private String name;
public Nameable(final String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
}
Now when you create the object for Make, Model and Year, they can all use this class so they can be used interchangeably, and can then be combined into a Car:
class Car
{
public final Nameable make;
public final Nameable model;
public final Nameable year;
public Car(Nameable make, Nameable model, Nameable year)
{
this.make = make;
this.model = model;
this.year = year;
}
public Nameable getInfo(final String info)
{
switch(info)
{
case "make": return this.make;
case "model": return this.model;
case "year": return this.year;
}
return null;
}
}
Then a simple implementation would be:
class PaganiZonda2006 extends Car
{
public PaganiZonda2006()
{
super(new Nameable("Pagani"), new Nameable("Zonda"), new Nameable("2006"));
}
}
And finally, when you want to get the information out, you can read it like so:
public static void main(String[] args)
{
Car car = new PaganiZonda2006();
System.out.println(car.getInfo("make").getName()); //Pagani
System.out.println(car.getInfo("model").getName()); //Zonda
System.out.println(car.getInfo("year").getName()); //2006
}
This ended up being my final solution which is a combination of MrLore and Sotirios Delimanolis solutions. This solution is completely dynamic without the use of any conditions.
This class performs the search for the name by passing in the property name;
String propertyName = "vehicleYear";
vehicleConfiguration.getInfo(propertyName).getName()
propertyName = "vehicleMake";
vehicleConfiguration.getInfo(propertyName).getName()
This class represents the VehicleConfiguration
#Entity
public class VehicleConfiguration extends StatefulEntity {
#ManyToOne
#JoinColumn(name = "year_id")
private VehicleYear vehicleYear;
#ManyToOne
#JoinColumn(name = "make_id")
private VehicleMake vehicleMake;
public LookupBaseEntity getInfo(final String fieldName) {
try {
String methodName = WordUtils.capitalize(fieldName);
Method method = VehicleConfiguration.class.getMethod("get" + methodName);
return (LookupBaseEntity) method.invoke(this);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(VehicleConfiguration.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
This class represents the VehicleYear
#Entity
public class VehicleYear extends LookupBaseEntity {
}
This class represents the VehicleMake
#Entity
public class VehicleMake extends LookupBaseEntity {
}
Which both extend LookupBaseEntity
public class LookupBaseEntity extends StatefulEntity {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

String Array object in Java

I am trying to print the first element on the two arrays in my Athlete class, country and name. I also need to create a object that simulates three dive attemps an athlete had (that is initially set to zero). I am new to OOP and I dont know how to go abouts doing this in my main... as far as constructors go. This is what i have done so far...
this is the main:
import java.util.Random;
import java.util.List;
public class Assignment1 {
public static void main(String[] args) {
Athlete art = new Athlete(name[0], country[0], performance[0]);
}
}
I just really am not sure what to do...
And this is the class with the arrays.
import java.util.Random;
import java.util.List;
public class Athlete {
public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germant", "USA"};
//Here i would like to create something that would be representing 3 dive attemps (that relate to dive and score. eventually.)
Athlete(String[] name, String[] country, Performance[] performance) {
this.name = name;
this.country=country;
this.performance=performance;
}
public Performance Perform(Dive dive){
dive.getDiveName();
return null;
}
public String[] getName() {
return name;
}
public void setName(String[] name) {
this.name = name;
}
public String[] getCountry() {
return country;
}
public void setCountry(String[] country) {
this.country = country;
}
}
thanks in advance for any help and input!
btw there is other classes too, just not relevant atm..
First, as for your Athlete class, you can remove your Getter and Setter methods since you have declared your instance variables with an access modifier of public. You can access the variables via <ClassName>.<variableName>.
However, if you really want to use that Getter and Setter, change the public modifier to private instead.
Second, for the constructor, you're trying to do a simple technique called shadowing. Shadowing is when you have a method having a parameter with the same name as the declared variable. This is an example of shadowing:
----------Shadowing sample----------
You have the following class:
public String name;
public Person(String name){
this.name = name; // This is Shadowing
}
In your main method for example, you instantiate the Person class as follow:
Person person = new Person("theolc");
Variable name will be equal to "theolc".
----------End of shadowing----------
Let's go back to your question, if you just want to print the first element with your current code, you may remove the Getter and Setter. Remove your parameters on your constructor.
public class Athlete {
public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germany", "USA"};
public Athlete() {
}
In your main method, you could do this.
public static void main(String[] args) {
Athlete art = new Athlete();
System.out.println(art.name[0]);
System.out.println(art.country[0]);
}
}
Currently you can't access the arrays named name and country, because they are member variables of your Athelete class.
Based on what it looks like you're trying to do, this will not work.
These arrays belong in your main class.
Your attempt at an athlete class seems to be dealing with a group of athletes, which is a design fault.
Define a class to represent a single athlete, with fields that represent the athlete's attributes:
public class Athlete {
private final String name;
private final String country;
private List<Performance> performances = new ArrayList<Performance>();
// other fields as required
public Athlete (String name, String country) {
this.name = name;
this.country = country;
}
// getters omitted
public List<Performance> getPerformances() {
return performances;
}
public Performance perform(Dive dive) {
// not sure what your intention is here, but something like this:
Performance p = new Performance(dive, this);
// add new performance to list
performances.add(p);
return p;
}
}
Then your main method would use ti like this:
public class Assignment1 {
public static void main(String[] args) {
String[] name = {"Art", "Dan", "Jen"};
String[] country = {"Canada", "Germant", "USA"};
Dive[] dive = new Dive[]{new Dive("somersault"), new Dive("foo"), new Dive("bar")};
for (int i = 0; i < name.length; i++) {
Athlete athlete = new Athlete(name[i], country[i]);
Performance performance = athlete.perform(dive[i]);
// do something with athlete and/or performance
}
}
}
I think you are a little messed up with what you doing.
Athlete is an object, athlete has a name, i has a city where he lives.
Athlete can dive.
public class Athlete {
private String name;
private String city;
public Athlete (String name, String city){
this.name = name;
this.city = city;
}
--create method dive, (i am not sure what exactly i has to do)
public void dive (){}
}
public class Main{
public static void main (String [] args){
String name = in.next(); //enter name from keyboad
String city = in.next(); //enter city form keybord
--create a new object athlete and pass paramenters name and city into the object
Athlete a = new Athlete (name, city);
}
}
public static void main(String[] args) {
public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germant", "USA"};
// initialize your performance array here too.
//Your constructor takes arrays as an argument so you need to be sure to pass in the arrays and not just objects.
Athlete art = new Athlete(name, country, performance);
}
First off, the arrays are pointless, let's get rid of them: all they are doing is providing values for mock data. How you construct mock objects has been debated ad nauseum, but clearly, the code to create the fake Athletes should be inside of a unit test. I would use Joshua Bloch's static builder for the Athlete class, but you only have two attributes right now, so just pass those in a Constructor. Would look like this:
class Athlete {
private String name;
private String country;
private List<Dive> dives;
public Athlete(String name, String country){
this.name = name;
this.country = country;
}
public String getName(){
return this.name;
}
public String getCountry(){
return this.country;
}
public String getDives(){
return this.dives;
}
public void addDive(Dive dive){
this.dives.add(dive);
}
}
Then for the Dive class:
class Dive {
private Athlete athlete;
private Date date;
private double score;
public Dive(Athlete athlete, double score){
this.athlete = athlete;
this.score = score;
this.date = new Date();
}
public Athlete getAthlete(){
return this.athlete;
}
public Athlete getAthlete(){
return this.athlete;
}
public Athlete getAthlete(){
return this.athlete;
}
}
Then make a unit test and just construct the classes, and manipulate them, make sure that they are working. Right now they don't do anything so all you could do is assert that they are retaining the Dives that you are putting in them. Example:
#Test
public void testThatDivesRetainInformation(){
Athlete art = new Athlete("Art", "Canada");
Dive art1 = new Dive(art, 8.5);
Dive art2 = new Dive(art, 8.0);
Dive art3 = new Dive(art, 8.8);
Dive art4 = new Dive(art, 9.2);
assertThat(art.getDives().size(), is(5));
}
Then you could go through and add tests for things like, making sure that you can't construct a dive without an athlete, etc.
You could move construction of the athletes into the setup method of the test so you could use it all over the place. Most IDEs have support for doing that with a refactoring.

Casting objects via reflection in Java

I am writing a deserializer method, which looks like so:
public <T> T deserialize(Object[] result, String[] fields, Class<T> type);
So basically I will be passed in a result array of data which is all objects, and a class type T which I need to convert the data in the array to the types in the given class, and create a new class of type T and return it. The String[] fields is the field names corresponding to the data in Object[] result. The field names will correspond to the Class T.
The casting will need to use reflection of the given class to find out the type of each field.
eg.
result = ["Mike", "London", 28];
fields = ["name", "location", "age" ];
Class T =
public class GivenClass{
private String name;
private String location;
private Integer age;
public GivenClass(String name, String location, Integer age){
this.name = name;
this.location = location;
this.age = age;
}
}
Class implementation
static class GivenClass {
private String name;
private String location;
private Integer age;
public GivenClass(String name, String location, Integer age) {
this.name = name;
this.location = location;
this.age = age;
}
public GivenClass(Map<String, Object> data) throws Exception {
for (Field f : GivenClass.class.getDeclaredFields())
f.set(this, data.get(f.getName()));
}
public Map<String, Object> serialize() throws Exception {
Map<String, Object> fields = new HashMap<String, Object>();
for (Field f : GivenClass.class.getDeclaredFields())
fields.put(f.getName(), f.get(this));
return fields;
}
#Override
public String toString() {
return "age=" + age + ", location=" + location + ", name=" + name;
}
}
Example:
public static void main(String[] args) throws Exception {
GivenClass o1 = new GivenClass("Mike", "London", 28);
Map<String, Object> serialized = o1.serialize();
GivenClass o2 = new GivenClass(serialized);
System.out.println(o2.toString());
}
Output:
age=28, location=London, name=Mike
You need to do the conversion yourself. Reflections doesn't convert (it will only check the type of an object is already correct)
Reflections won't give you the names of method/constructor parameters. (You can get them from the debug byte code but that's a real pain)
The approach I take is to use the convention that the constructor parameters are in the same order as the fields. You will also want to assume the type of constructor parameters and field types match. ;)
I would also use primitives instead of wrappers whenever possible. Use int unless you want null to be a valid option. If this is the case you should think about how you want to represent this. For text I usually use empty strings or blank field for null or NaN depending on the context.
The problem with this, is that in Java it's unable to fetch the parameter names of a constructor.
For this particular example, you'll need a default constructor, with which you could create an empty object.
public GivenClass() {
super();
}
Then you could use reflection to get the fields of the class, and then set the appropriate value for them.
But I think it would be much easier to annotate your constructor, and then fetch the annotation informations in your deserialize method. In this case you won't need to fetch the fields and create an empty constructor.
Example:
You need to create a annotation like this:
#Target({ElementType.PARAMETER})
#Retention(RetentionPolicy.RUNTIME)
public #interface Property
{
String value();
}
And then you can use it in your constructor like this:
public GivenClass(#Property("name") String name, #Property("location") String location, #Property("age") Integer age) {
// ...
}
As Peter Lawrey says, casting does not convert a string into an integer.
If your bean follows the standard bean conventions (ie you have getters & setters), then you can use BeanUtils. BeanUtils does some standard conversions, and you can add more by adding a Convertor.
See the following example:
import org.apache.commons.beanutils.BeanUtils;
public class BeanUtilsTest {
public static class Obj {
private int number;
private String string;
public void setNumber(int number) {
this.number = number;
}
public void setString(String string) {
this.string = string;
}
public String toString() {
return "number=" + number + " string=" + string;
}
}
public static void main(String args[]) throws Exception {
String[] values = new String[] { "1", "two" };
String[] properties = new String[] { "number", "string" };
Obj obj = new Obj();
for (int i = 0; i < properties.length; i++) {
BeanUtils.setProperty(obj, properties[i], values[i]);
}
System.out.println("obj=" + obj);
}
}
This produces as output:
obj=number=1 string=two
Note that the above example has only setters, but still works.

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