This is the test class that I have an error in and I cant figure out what it is exactly.
import java.util.*;
public class EmployeeTest
{
public static void main(String[] args) {
Employee e = new Employee();
e.setId("100012");
e.setLastname("Smith");
ResponsibilityDecorator d;
d = new Recruiter(e);
d = new CommunityLiaison(e);
d = new ProductionDesigner(e);
System.out.println(e.toString());
}
}
And this the class that links to the test class
public class Employee
{
String id;
String lastname;
Employee(String id, String lastname)
{
this.id=id;
this.lastname=lastname;
}
EmploymentDuties eduties=new EmploymentDuties();
public EmploymentDuties getDuties()
{
return eduties;
}
public String toString(){
return "Duties for this employee: "+eduties.jobtitles;
}
public void setId(String id)
{
this.id = id;
}
public void setLastname(String lastname)
{
this.lastname = lastname;
}
}
There is no no-args constructor in Employee. Add parameters to use the existing constructor in EmployeeTest
Employee e = new Employee("100012", "Smith");
the statements
e.setId("100012");
e.setLastname("Smith");
are then redundant and can be removed.
Your class Employee defines exactly one constructor: Employee(String, String). Make sure you call it from the EmployeeTest or define a no parameter constructor.
The default constructor is the constructor provided by the java in the absence of any constructor provided by the you.
Once you supplies any constructor , the default constructor is no longer supplied.
you created constructor
Employee(String id, String lastname)
{
and using like
Employee e = new Employee(); //not possible
The default constructor is the no-argument constructor automatically generated unless you define another constructor.
This is the default constructor :
Employee() {}
Then you can instantiate objects like :
Employee e = new Employee();
if you define at least one constructor explicitly , the default constructor is not generated.
Related
Customer is a class. The Class list is arraylist of Customer.
I have added the Customers to list but when I want to print all the customer names from the list I get null only.
import java.util.*;
public class Assignment1 {
public static void main(String args[])
{
List list = new List();
list.addCustomer("man");
list.addCustomer("man");
//System.out.println(list);
list.printx();
}
}
class Customer{
public String name;
public Customer(String name)
{
name = this.name;
}
}
class List
{
ArrayList<Customer> list = new ArrayList<Customer>();
public void addCustomer(String name1)
{
Customer x = new Customer(name1);
list.add(x);
System.out.println(list.get(0));
}
public void printx()
{
for(int i =0;i < list.size();i++)
{
System.out.println(list.get(i).name);
}
}
}
Inside your Customer constructor, you need to set ::
this.name = name;
and not the other way round! :P
What you have done right now is that you change the function parameter name to the class parameter name which is currently null(default initialization). So, you never initialize name variable of the Customer class, and hence you always get null when you print it.
I suggest you override the toString method in class Customer, it helps you debug your Customer objects. For example, you can change the local variable to assignedName as below:
class Customer{
public String name;
public Customer(String name)
{
this.name = name;
}
#Override
public String toString(){
return "customer name:" + this.name;
}
}
this.name and name are different things in the Customer constructor:
this.name is an instance variable and name is a local variable defined in your constructor.
// you should narrow the modifier to private, and implement getter and setter for it
public String name;
public Customer(String assignedName){
this.name = assignedName;
}
I have a PersonFactory interface as follows:
#FunctionalInterface
public interface PersonFactory<P extends Person> {
P create(String firstname, String lastname);
// Return a person with no args
default P create() {
// Is there a way I could make this work?
}
}
The Person class:
public class Person {
public String firstname;
public String lastname;
public Person() {}
public Person(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
}
I want to be able to instantiate my Persons like this:
PersonFactory<Person> personFactory = Person::new;
Person p = personFactory.create(); // does not work
Person p = personFactory.create("firstname", "lastname"); // works
Is there a way I could make the Java compiler automatically choose the right constructor by matching the signature of PersonFactory.create() ?
One way would be to have the following:
default P create() {
return create(null, null);
}
But I'm not sure that's what you wanted. The problem is that you can't make a method reference refer to 2 different methods (or constructors). In this case, you want Person::new to refer to the constructor taking no parameters and the constructor taking 2 parameters, which is not possible.
When you have:
#FunctionalInterface
public interface PersonFactory<P extends Person> {
P create(String firstname, String lastname);
}
and use it like
PersonFactory<Person> personFactory = Person::new;
Person p = personFactory.create("firstname", "lastname");
you have to realize that the method-reference Person::new refers to the constructor taking 2 parameters. The next line just invokes it by passing the parameters.
You could also write it more explicitely using a lambda expression:
PersonFactory<Person> personFactory = (s1, s2) -> new Person(s1, s2); // see, we have the 2 Strings here
Person p = personFactory.create("firstname", "lastname");
Recently I discovered ActiveObejcts and I really like it. Right now I'm using the last version from Atlassian plugin, only the net.java.ao part for ORM. Compiles and runs fine. Sure, I have to do some performance tests, if it fits my requirements.
There exists the #Implementation annotation. How is that used? The javadocs are very brief.
Update
Solution:
public class M5 {
public static void main(String[] args) throws SQLException {
EntityManager m = EntityManagerBuilder
.url("jdbc:hsqldb:./db/db")
.username("root")
.password("")
.c3po()
.build();
m.migrate(Employee.class);
Employee p = m.create(Employee.class);
p.setFirstName("Peter");
p.setLastName("Mmm");
System.err.println(p.getLastName()); // prints "ln: Mmm"
p.save();
}
}
public class Emp {
private Employee employee;
public Emp(Employee employee) {
this.employee = employee;
}
public String getLastName() {
return "ln: " + employee.getLastName();
}
}
#Implementation(Emp.class)
interface Employee extends Entity {
String getFirstName();
void setFirstName(String name);
String getLastName();
void setLastName(String name);
}
}
Active Objects takes your interface and, via reflection through a complicated proxy translates your getters, setters and relations into SQL statements. If you want some of your own code in there to add or modify functionality of your AO interface, you can use #Implementation
Example:
AO interface:
#Implementation(PersonImpl.class)
public interface Person extends Entity {
String getLastName();
void setLastName(String name);
String getFirstName();
void setFirstName(String name);
#Ignore
String getName();
}
Implementation:
public class PersonImpl {
private final Person person; // this will be the original entity proxy
public PersonImpl(Person person) {
this.person = person;
}
// "Implement" ignored functions
public String getName() {
return String.format("%s %s", this.person.getFirstName(), this.person.getLastName());
}
// "Enhance" AO getters/setters
public void setFirstName(String name) {
this.person.setFirstName("Foobar");
}
}
Note that AO accesses these implementation methods via reflection. They must match the names in the interface. This might lead to problems during refactorings, as method names might change and your compiler won't tell you that your corresponding impl method name hasn't.
Is that possible to initialize object directly as we can do with String class in java:
such as:
String str="something...";
I want to do same for my custom class:
class MyData{
public String name;
public int age;
}
is that possible like
MyClass obj1={"name",24};
or
MyClass obj1="name",24;
to initialize object?
or how it can be possible!
Normally, you would use a constructor, but you don't have to!
Here's the constructor version:
public class MyData {
private String name;
private int age;
public MyData(String name, int age) {
this.name = name;
this.age = age;
}
// getter/setter methods for your fields
}
which is used like this:
MyData myData = new MyData("foo", 10);
However, if your fields are protected or public, as in your example, you can do it without defining a constructor. This is the closest way in java to what you want:
// Adding special code for pedants showing the class without a constuctor
public class MyData {
public String name;
public int age;
}
// this is an "anonymous class"
MyData myData = new MyData() {
{
// this is an "initializer block", which executes on construction
name = "foo";
age = 10;
}
};
Voila!
If you have a class Person:
public class Person {
private String lastName;
private String firstName;
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
You can actually create a new Person object and initialize its firstName and lastName with the following:
Person person = new Person(){{
setFirstName("My FirstName");
setLastName("MyLastName");
}}
This is used quite often when defining Spring Configuration using Java code instead of XML configuration.
You have to make a constructor method for the object, which takes in parameters of the fields you want values for.
Example:
public myClass( int age, String name)
{
this.age = age;
this.name = name;
}
Then in the class you want this:
myClass class = new myClass(24, "name");
I know that with constructors, but any alternative way is present or not?
No, there are no alternatives to constructors.
That's basically one of the fundamental guarantees of the language. An object can't be constructed by any other means than through its constructors and there's no alternative syntax then the usual new ConstructorName(...).
The closest idea I can come up with would be to have a static factory method called say, mc:
class MyClass {
...
public static mc(String name, int age) {
return new MyClass(name, age);
}
}
and then do
import static some.pkg.MyClass.mc;
...
MyClass obj1 = mc("name",24);
It is possible with the keyword new and using constructors, but not like the String, that is a very special kind of object.
class MyData{
public MyData(String name, int age) {
this.name = name;
this.age = age;
}
public String name;
public int age;
}
Then you can instantiate your class this way:
MyData myData = new MyData("name", 24);
package com.company;
public class InitializationOfObject {
int a ;
int b ;
InitializationOfObject(){
}
InitializationOfObject( int r , int n){
this.a = r;
this.b = n;
System.out.println("Object initialization by constructor ");
}
void methodInitialization(int k, int m){
System.out.println("object initialization via method");
this.a = k;
this.b = m;
}
void display(){
System.out.println("k = " +a+ "m = "+b);
}
public static void main(String... arg){
InitializationOfObject io = new InitializationOfObject();
InitializationOfObject io2 = new InitializationOfObject(45,65);
io.a = io2.a;
io.b = io2.b;
io.display();
io.methodInitialization(34,56);
io.display();
io.a = 12;
io.b = 24;
System.out.println("object initialization via refrence");
System.out.println("a = "+io.a+" "+ " b ="+io.b);
}
}
//Object initializatian by construtor
k = 45m = 65
object initializaion via method
k = 34m = 56
object initialization via reference
a = 12 b =24
There are two types of Constructors in java.
Default constructor
Parameterized constructor
You should create a parameterized constructor to create your object.
The following does what you want, but not in the way that you would expect.
So in a class calling MyData, you would use
Public MyData x = new MyData();
#PostConstruct public void init() {
x.setName("Fering");
x.setAge(18);
}
So once the object is construsted, these commands are run, which allows you to populate the object before anything else runs.
So with this you do not have to use anonymous subclasses, or create new constructors, you can just take the class and then use its functions, before anything else would.
There is no alternative to constructors (along with new operator) in java during the object initialization. You have mentioned as
String str = "something"
you can initialize string that way, because String is a literal in java. Only literals can initialized that way. A a composite object can not initialized, but only can be instantiated with the new operator with the constructors.
class Person {
String name = “No name";
public Person(String nm) { name = nm; }
}
class Employee extends Person {
String emplD = “0000”;
public Employee(String id) { empID = id; }
}
public class EmployeeTest {
public static void main(String[ ] args)
{
Employee e = new Employee(”4321”);
System.out.println(e.empID);
}
}
The constructor of Employee must call its super constructor, the constructor of Person.
public class Person
{
private String name;
public Person(String nm)
{
this.name = nm;
}
public String getName()
{
return this.name;
}
}
public class Employee extends Person
{
private String emplD;
public Employee(String nm, String id)
{
super(nm);
this.empID = id;
}
public String getId()
{
return this.empID;
}
}
public class EmployeeTest
{
public static void main(String[] args)
{
Employee e = new Employee("Some Name", "4321");
System.out.println(e.getID());
}
}
Change “No name’ into “No name" (closing quotes)
Maybe it's here:
String name = “No name’;
should it be:
String name = "No name";
Also, I'm not sure if this is the editor that you've pasted it in from doing this, but this is wrong too:
Employee e = new Employee(”4321”);
should be:
Employee e = new Employee("4321");
A number of things:
You're using the wrong kind of quote characters around your strings. You need to use ". Not “, ', or ”.
Your Person class has no default constructor. Because of this you must explicitly call super("some name"); as the first line of your Employee constructor (I would suggest adding a constructor that takes both name and employeeId as parameters).
You declared the property as emplD (with a lower-case L character), but you try to assign to it as empID (with an uppercase I character). You can call it whatever you want, but the name needs to match in both places.
Your object design violates the basic principles of encapsulation. The name and empID properties should be private fields, and if external classes need access to these values, then you should provide the appropriate public getter methods. In other words, instead of e.empID you should be able to say e.getEmpID().
It is generally not good coding style to define multiple classes in a single file, particularly when all of them are meant to be publicly accessible.
Change this line
String name = “No name’;
to:
String name = “No name";
check your closing qoutes.
Your empID field is not public / there is no accessor method for it / it is not defined as a property. Also don't expect people to help if you provide absolutely no information on the error other than the source code and a vague post title.
You have to call the constructor of the superclass (Person) in the constructor of the class `Employeesuper(id); Please find the correct code below.
public Employee(String id) {super(id);empID =id;
Calling a super class constructor would fix the issue !
public class Person {
String name = "No name";
public Person(String nm) { name = nm; }
}
public class Employee extends Person {
String empID = "0000";
public Employee(String id) {
super("Some Name");
empID = id; }
}
public class EmployeeTest {
public static void main(String[] args){
Employee e = new Employee("4321");
System.out.println(e.empID);
}
}