Passing HashMap as parameter into a subclass constructor - hashmap

I've been struggling with trying to figure out the problem and fixing the error when I tried to pass HashMap into a constructor. My scenario is:
I've a Student class:
public class Student {
String name;
String major;
String level;
public Student (String name, String major, String level) {
this.name = name;
this.major = major;
this.level = level;
}
}
I've another class, called TA_Manager that is a subclass of Student. This TA_Manager class uses HashMap to collect the students (who are TA) from the Student class:
import java.util.HashMap;
public class TA_Manager extends Student {
HashMap<String, Student> TA;
public TA_Manager(HashMap<String, Student> TA) {
this.TA = TA;
}
}
In the main class, I've created three student objects and I put two of the students into the HashMap (they are TAs). Then I create a TA_Manager object and pass the HashMap into the TA_Manager class:
import java.util.HashMap;
public class Test {
public static void main(String[] args) {
Student s1 = new Student("A", "CS", "Junior");
Student s2 = new Student("B", "IS", "Senior");
Student s3 = new Student("C", "CE", "Senior");
HashMap<String, Student> TA = new HashMap<String, Student>();
TA.put("TA1", s1);
TA.put("TA2", s2);
TA_Manager tamgr = new TA_Manager (TA);
}
}
When I run the main class, it returns error:
TA_Manager.java:6: error: constructor Student in class Student cannot be applied to given types;
public TA_Manager(HashMap<String, Student> TA) {
^
required: String,String,String
found: no arguments
I actually have searched this HashMap problem and I followed the solution given on how to pass the HashMap into the constructor:
Pass a HashMap as parameter in Java
and also from this link on how to pass a class as hashmap value:
Can HashMap contain custom class for key/value?
But I still get the error message. I don't know how to fix this error. Can anyone bring some light into this. Really appreciated.

The error is caused because java is trying to call the no-arg constructor of your Student class, but you only have a three argument public constructor.
The simplest solution is to create an empty public constructor for your student.
public Student(){
//do nothing and leave values as null.
}
This is not a very practical solution. The problem is a bit conceptual. Your TA class is a Student, but you don't give it a name major or level.
The next way to manage this would be to call the current constructor with some values.
public TA_Manager(HashMap<String, Student> TA) {
super( null, null, null);
this.TA = TA;
}
Now java knows to use the public constructor instead of the no-arg one. I left the values as null because I don't know what default values you would have. This is practical when there are useful default values that you wouldn't need to include during construction.
Personally, I would expect the TA to be a full student AND have a hashmap.
public TA_Manager (String name, String major, String level) {
super(name, major, level);
this.TA = new HashMap<>();
}
In this case you would create the manager, then add all of the students afterwards. It has the advantage that your TA_Manager is a fully formed student though.

Related

How to mock the Data Stax Row object[com.datastax.driver.core.Row;] - Unit Test

Please find the below code for the DAO & Entity Object and Accessor
#Table(name = "Employee")
public class Employee {
#PartitionKey
#Column(name = "empname")
private String empname;
#ClusteringColumn(0)
#Column(name = "country")
private String country;
#Column(name = "status")
private String status;
}
Accessor:
#Accessor
public interface EmployeeAccessor {
#Query(value = "SELECT DISTINCT empname FROM EMPLOYEE ")
ResultSet getAllEmployeeName();
}
}
DAO getAllEmployeeNames returns a List which are employee names
and it will be sorted in ascending order.
DAO
public class EmployeeDAOImpl implements EmployeeDAO {
private EmployeeAccessor employeeAccessor;
#PostConstruct
public void init() {
employeeAccessor = datastaxCassandraTemplate.getAccessor(EmployeeAccessor.class);
}
#Override
public List<String> getAllEmployeeNames() {
List<Row> names = employeeAccessor.getAllEmployeeName().all();
List<String> empnames = names.stream()
.map(name -> name.getString("empname")).collect(Collectors.toList());
empnames.sort(naturalOrder()); //sorted
return empnames;
}
}
JUnit Test(mockito):
I am not able to mock the List[datastax row]. How to mock and returns a list of rows with values "foo" and "bar".Please help me in unit test this.
#Category(UnitTest.class)
#RunWith(MockitoJUnitRunner.class)
public class EmployeeDAOImplUnitTest {
#Mock
private ResultSet resultSet;
#Mock
private EmployeeAccessor empAccessor;
//here is the problem....how to mock the List<Row> Object --> com.datastax.driver.core.Row (interface)
//this code will result in compilation error as we are mapping a List<Row> to the ArrayList<String>
//how to mock the List<Row> with a list of String row object
private List<Row> unSortedTemplateNames = new ArrayList() {
{
add("foo");
add("bar");
}
};
//this is a test case to check if the results are sorted or not
//mock the accessor and send rows as "foo" & "bar"
//after calling the dao , the first element must be "bar" and not "foo"
#Test
public void shouldReturnSorted_getAllTemplateNames() {
when(empAccessor.getAllEmployeeName()).thenReturn(resultSet);
when(resultSet.all()).thenReturn(unSortedTemplateNames); //how to mock the List<Row> object ???
//i am testing if the results are sorted, first element should not be foo
assertThat(countryTemplates.get(0), is("bar"));
}
}
Wow! This is overly complex, hard to follow, and not an ideal way to write unit tests.
Using PowerMock(ito) along with "static" references in your own code is not recommended and is a sure sign of a code smells.
First, I am not sure why you decided to use a static reference (e.g. EmployeeAccessor.getAllEmployeeName().all(); inside the EmployeeDAOImpl class, getAllEmployeeNames() method) instead of using the instance variable (i.e. empAccessor), which is more conducive to actual "unit testing"?
The EmployeeAccessor, getAllEmployeeName() "interface" method is not static (clearly). However, seemingly, whatever this (datastaxCassandraTemplate.getAccessor(EmployeeAccessor.class);) generates makes it so (really?), which then requires the use of PowerMock(ito), o.O
Frameworks like PowerMock, and extensions of (i.e. "PowerMockito"), were meant to test and mock code used by your application (unfortunately, but necessarily so) where this "other" code makes use of statics, Singletons, private methods and so on. This anti-pattern really ought not be followed in your own application design.
Second, it is not really apparent what the "Subject Under Test" (SUT) is in your test case. You implemented a test class (i.e. EmployeeDAOImplTest) for, supposedly, your EmployeeDAOImpl class (the actual "SUT"), but inside your test case (i.e. shouldReturnSorted_getAllTemplateNames()), you are calling... countryLocalizationDAOImpl.getAllTemplateNames(); thus testing the CountryLocalizationDAOImpl class (??), which is not the "SUT" of the EmployeeDAOImplTest class.
Additionally, it is not apparent that the EmployeeDAOImpl even uses a CountryLocalizationDAO instance (assuming an interface here as well), and if it does, then it is certainly something that should be "mocked" when the EmployeeDAOImpl "interacts" with instances of CountryLocalizationDAO, particularly in the context of a unit test. The only correlation between the EmployeeDAO and CountryLocalizationDAO is that the Employee has a country field.
There are a few other problems with your design/setup as well, but anyway.
Here are a few suggestions...
First, let's test what your EmployeeDAOImplTest is meant to test... EmployeeDAO.getAllEmployeeNames() in a sorted fashion. This in turn may give you ideas of how to test your "CountryLocalizationDAO, getAllTemplateNames() method perhaps (if it even makes sense, i.e. getAllTemplateNames() is in fact dependent on an Employee's country, when Employees are ordered by name (i.e. "empname" and accessed via EmployeeAccessor).
public class EmployeeDAOImpl implements EmployeeDAO {
private final EmployeeAccessor employeeAccessor;
// where does the DataStaxCassandraTemplate reference come from?!
private DataStaxCassadraTemplate datastaxCassandraTemplate = ...;
public EmployeeDAOImpl() {
this(datastaxCassandraTemplate.getAccessor(EmployeeAccessor.class));
}
public EmployeeDAOImpl(EmployeeAccessor employeeAccessor) {
this.employeeAccessor = employeeAccessor;
}
protected EmployeeAccessor getEmployeeAccessor() {
return this.empAccessor;
}
public List<String> getAllEployeeNames() {
List<Row> nameRows = getEmployeeAccessor().getAllEmployeeName().all();
...
}
}
Then in your test class...
public class EmployeeDAOImplUnitTest {
#Mock
private EmployeeAccessor mockEmployeeAccessor;
// SUT
private EmployeeDAO employeeDao;
#Before
public void setup() {
employeeDao = new EmployeeDAOImpl(mockEmployeeAccessor);
}
protected ResultSet mockResultSet(Row... rows) {
ResultSet mockResultSet = mock(ResultSet.class);
when(mockResultSet.all()).thenReturn(Arrays.asList(rows));
return mockResultSet;
}
protected Row mockRow(String employeeName) {
Row mockRow = mock(Row.class, employeeName);
when(mockRow.getString(eq("empname")).thenReturn(employeeName);
return mockRow;
}
#Test
public void getAllEmployeeNamesReturnsSortListOfNames() {
when(mockEmployeeAccessor.getAllEmployeeName())
.thenReturn(mockResultSet(mockRow("jonDoe"), mockRow("janeDoe")));
assertThat(employeeDao.getAllEmployeeNames())
.contains("janeDoe", "jonDoe");
verify(mockEmployeeAccessor, times(1)).getAllEmployeeName();
}
}
Now, you can apply similar techniques if in fact there is an actual correlation between Employees and CountryLocalizationDAO via the EmployeeAccessor.
Hope this helps get you on a better track!
-j

initializing derived class member variables using base class reference object

I came across a lot of code in our company codebase with the following structure
class Base
{
public Base (var a, var b)
{
base_a = a;
base_b = b;
}
var base_a;
var base_b;
}
class Derived:Base
{
publc Derived (var a,b,c,d): base (a,d)
{
der_c = c;
der_d = d;
}
var der_c;
var der_d;
var der_e;
}
class Ref
{
Base _ref;
public Ref( var a,b,c,d)
{
_ref = new Derived (a,b,c,d)
}
public void method( )
{
_ref.der_e = 444; // won't compile
}
}
What is the correct way to initialize der_e ? What is the advantages of having a reference of base class and using an object derived class for _ref ? Just the fact that using a base class reference can hold multiple derived class objects ? If that's the case, should all the member variables of derived class be initialized during construction itself (like this: _ref = new Derived (a,b,c,d) ). What if I want to initialize _ref.der_e later in a method ? I know I can do this (var cast_ref = _ref as Derived; cast_ref.der_e = 444) but this look doesn't seem to the best practice. What is the idea of having such a structure and what is the correct of initializing a member of a derived class object after it has been constructed ?
Those are too many questions in a single post.
What is the correct way to initialize der_e ?
For initializing der_e you will have to have Reference of Derived class as it knows about the der_e property and not Base class.
What is the advantages of having a reference of base class and using
an object derived class for _ref ?
Yes that's called Polymorphism which is the essence of Object Oriented Programming. It allows us to hold various concrete implementations without knowing about the actual implementation.
If that's the case, should all the member variables of derived class
be initialized during construction itself (like this: _ref = new
Derived (a,b,c,d) )
There is no such rule. It depends on your scenario. If the values are not meant to be changed after the creation of the object and the values are known before hand during construction of the object then they should be initialized during construction.
Again if there are various scenarios like sometimes values are known and sometimes not then there can be Overloaded Constructors, which take different arguments.
What if I want to initialize _ref.der_e later in a method ?
That is perfectly fine, it depends on what you are trying to achieve. The question is not a concrete one but an abstract one in which it is difficult to comment on what you are trying to achieve.
I know I can do this (var cast_ref = _ref as Derived; cast_ref.der_e =
444) but this look doesn't seem to the best practice.
I am sharing some Java code which is similar to C# as I am from Java background
//This class knows about Base and nothing about the Derived class
class UserOfBase{
Base ref;
//Constructor of UserOfBase gets passed an instance of Base
public UserOfBase(Base bInstance){
this.ref = bInstance;
}
//Now this class should not cast it into Derived class as that would not be a polymorphic behavior. In that case you have got your design wrong.
public void someMethod(){
Derived derivedRef = (Derived)ref; //This should not happen here
}
}
I am sharing some references which would help you with this, as I think the answer can be very long to explain.
Factory Pattern
Dependency Injection
Head First Design Patterns
Posts on SO regarding polymorphism
You can create a constructor in your derived class and map the objects or create an extension method like this:
public static class Extensions
{
public static void FillPropertiesFromBaseClass<T1, T2>(this T2 drivedClass, T1 baseClass) where T2 : T1
{
//Get the list of properties available in base class
System.Reflection.PropertyInfo[] properties = typeof(T1).GetProperties();
properties.ToList().ForEach(property =>
{
//Check whether that property is present in derived class
System.Reflection.PropertyInfo isPresent = drivedClass.GetType().GetProperty(property.Name);
if (isPresent != null && property.CanWrite)
{
//If present get the value and map it
object value = baseClass.GetType().GetProperty(property.Name).GetValue(baseClass, null);
drivedClass.GetType().GetProperty(property.Name).SetValue(drivedClass, value, null);
}
});
}
}
for example when you have to class like this:
public class Fruit {
public float Sugar { get; set; }
public int Size { get; set; }
}
public class Apple : Fruit {
public int NumberOfWorms { get; set; }
}
you can initialize derived class by this code:
//constructor
public Apple(Fruit fruit)
{
this.FillPropertiesFromBaseClass(fruit);
}

groovy: variable scope in closures in the super class (MissingPropertyException)

I have the impression that closures run as the actual class being called (instead of the implementing super class) and thus break when some variables are not visible (e.g. private in the super class).
For example
package comp.ds.GenericTest2
import groovy.transform.CompileStatic
#CompileStatic
class ClosureScopeC {
private List<String> list = new ArrayList<String>()
private int accessThisPrivateVariable = 0;
void add(String a) {
list.add(a)
println("before ${accessThisPrivateVariable} ${this.class.name}")
// do something with a closure
list.each {String it ->
if (it == a) {
// accessThisPrivateVariable belongs to ClosureScopeC
accessThisPrivateVariable++
}
}
println("after ${accessThisPrivateVariable}")
}
}
// this works fine
a = new ClosureScopeC()
a.add("abc")
a.add("abc")
// child class
class ClosureScopeD extends ClosureScopeC {
void doSomething(String obj) {
this.add(obj)
}
}
b = new ClosureScopeD()
// THIS THROWS groovy.lang.MissingPropertyException: No such property: accessThisPrivateVariable for class: comp.ds.GenericTest2.ClosureScopeD
b.doSomething("abc")
The last line throws a MissingPropertyException: the child class calls the "add" method of the super class, which executes the "each" closure, which uses the "accessThisPrivateVariable".
I am new to groovy, so I think there must be an easy way to do this, because otherwise it seems that closures completely break the encapsulation of the private implementation done in the super class ... this seems to be a very common need (super class implementation referencing its own private variables)
I am using groovy 2.1.3
I found this to be a good reference describing how Groovy variable scopes work and applies to your situation: Closure in groovy cannot use private field when called from extending class
From the above link, I realized that since you have declared accessThisPrivateVariable as private, Groovy would not auto-generate a getter/setter for the variable. Remember, even in Java, private variables are not accessible directly by sub-classes.
Changing your code to explicitly add the getter/setters, solved the issue:
package com.test
import groovy.transform.CompileStatic
#CompileStatic
class ClosureScopeC {
private List<String> list = new ArrayList<String>()
private int accessThisPrivateVariable = 0;
int getAccessThisPrivateVariable() { accessThisPrivateVariable }
void setAccessThisPrivateVariable(int value ){this.accessThisPrivateVariable = value}
void add(String a) {
list.add(a)
println("before ${accessThisPrivateVariable} ${this.class.name}")
// do something with a closure
list.each {String it ->
if (it == a) {
// accessThisPrivateVariable belongs to ClosureScopeC
accessThisPrivateVariable++
}
}
println("after ${accessThisPrivateVariable}")
}
}
// this works fine
a = new ClosureScopeC()
a.add("abc")
a.add("abc")
// child class
class ClosureScopeD extends ClosureScopeC {
void doSomething(String obj) {
super.add(obj)
}
}
b = new ClosureScopeD()
b.doSomething("abc")
There is a simpler way, just make the access modifier (should rename the property really) to protected, so the sub-class has access to the property.. problem solved.
protected int accessThisProtectedVariable
To clarify on your statement of concern that Groovy possibly has broken encapsulation: rest assured it hasn't.
By declaring a field as private, Groovy is preserving encapsulation by intentionally suspending automatic generation of the public getter/setter. Once private, you are now responsible and in full control of how or if there is a way for sub-classes (protected) or all classes of objects (public) to gain access to the field by explicitly adding methods - if that makes sense.
Remember that by convention, Groovy ALWAYS calls a getter or setter when your codes references the field. So, a statement like:
def f = obj.someField
will actually invoke the obj.getSomeField() method.
Likewise:
obj.someField = 5
will invoke the obj.setSomeField(5) method.

Does not contain a constructor that takes 0 arguments

I get an error stating "Products does not contain a constructor that takes 0 arguments" from the following code:
public class Products
{
string id;
string name;
double price;
int soldCount;
int stockCount;
public Products(string id, string name, double price,
int soldCount, int stockCount, double tax)
{
this.id = id;
this.name = name;
this.price = price;
this.soldCount = soldCount;
this.stockCount = stockCount;
}
}
//I have got some get and set values for the code above
//but it would have been too long to put in here
public class FoodProducts : Products
{
public FoodProduct()
{
Console.WriteLine("This is food product");
}
public void Limit()
{
Console.WriteLine("This is an Attribute of a Product");
}
}
Several rules about C# come into play here:
Each class must have a constructor (In order to be, well constructed)
If you do not provide a constructor, a constructor will be provided for you, free of change, automatically by the compiler.
This means that the class
class Demo{}
upon compilation is provided with an empty constructor, becoming
class Demo{
public Demo(){}
}
and I can do
Demo instance = new Demo();
If you do provide a constructor (any constructor with any signature), the empty constructor will not be generated
class Demo{
public Demo(int parameter){}
}
Demo instance = new Demo(); //this code now fails
Demo instance = new Demo(3); //this code now succeeds
This can seem a bit counter-intuitive, because adding code seems to break existing unrelated code, but it's a design decision of the C# team, and we have to live with it.
When you call a constructor of a derived class, if you do not specify a base class constructor to be called, the compiler calls the empty base class constructor, so
class Derived:Base {
public Derived(){}
}
becomes
class Derived:Base {
public Derived() : base() {}
}
So, in order to construct your derived class, you must have a parameterless constructor on the base class. Seeing how you added a constructor to the Products, and the compiler did not generate the default constructor, you need to explicitly add it in your code, like:
public Products()
{
}
or explicitly call it from the derived constructor
public FoodProduct()
: base(string.Empty, string.Empty, 0, 0, 0, 0)
{
}
Since Products has no constructor that takes 0 arguments, you must create a constructor for FoodProducts that calls the constructor of Products will all the required arguments.
In C#, this is done like the following:
public class FoodProducts : Products
{
public FoodProducts(string id, string name, double price, int soldCount, int stockCount, double tax)
: base(id, name, price, soldCount, stockCount, tax)
{
}
public void Limit()
{
Console.WriteLine("This is an Attribute of a Product");
}
}
If you don't want to add this constructor to FoodProducts, you can also create a constructor with no parameter to Products.
the constructor of the inherited class needs to construct the base class first. since the base class does not have a default constructor (taking 0 arguments) and you are not using the non-default constructor you have now, this won't work. so either A) add a default constructor to your base class, in which case the code of the descending class needs no change; or B) call the non-default constructor of the base class from the constructor of the descending class, in which case the base class needs no change.
A
public class Products
{
public Products() { }
}
public class FoodProducts : Products
{
public FoodProducts() { }
}
B
public class Products
{
public class Products(args) { }
}
public class FoodProducts : Products
{
public FoodProducts(args) : base(args) { }
}
some of this is explained rather OK on msdn here.
As you inherit from Products, you must call a base construct of Products in your own class.
You didn't write:base(id, name, ....) so C# assumes you call the default parameterless constructor, but it doesn't exist.
Create a default parameterless constructor for Products.
Just add
public Products()
{
}
in your products class And you will not get error
Reason:
There exists a default constructor with 0 parameter for every class. So no need to define/write it explicitly (by programmer) BUT when you overload a default constructor with your desired number and type of parameters then it becomes a compulsion to define the default constructor yourself (explicitly) along with your overloaded constructor

I want to know theoretical thing about programming

I'm not sure about one thing. There are two things in object oriented programming.
Constructor
Method
Which one of these can be overloaded and which one overridden?
Thanks!
both can be overloaded.
overloading means having two or more methods or constructors with exactly same name but different signatures. some thing like :
public myClass(String a){}
public myClass(Double d){}
or for methods :
public void aMethod(String s){}
publis int aMethod(Double d){
return 0;
}
edited :
bebin, overriding usually comes with inheritance , when the super class implements a method but the subclass needs to implement that method in other way like :
in super class:
public int doSomething(){
return a+2;
}
but in subclass :
#override
public in doSomething(){
return a*2;
}
and about constructor overriding the following line are from CollinD and i am quoting it :
"Constructors are not normal methods and they cannot be "overridden". Saying that a constructor can be overridden would imply that a superclass constructor would be visible and could be called to create an instance of a subclass. This isn't true... a subclass doesn't have any constructors by default (except a no-arg constructor if the class it extends has one). It has to explicitly declare any other constructors, and those constructors belong to it and not to its superclass, even if they take the same parameters that the superclass constructors take.
The stuff you mention about default no arg constructors is just an aspect of how constructors work and has nothing to do with overriding."
That may depend on the language, but theoretically both can be both overloaded and overridden.
C# examples of everything:
class Parent {
protected string Name;
public Parent(string name) {
this.Name = name;
}
public Parent(string firstName, string lastName) {
this.Name = firstName + " " + lastName;
}
public virtual string GetName() {
return this.Name;
}
}
class Child : Parent {
public Child(string firstName) : base(firstName, "Doe") {}
public override string GetName() {
return this.Name = " Jr.";
}
public string GetName(string prefix) {
return prefix + " " + this.GetName();
}
}
This illustrates constructor and method overriding and constructor and method overloading.
You can overload and override both constructors and methods. (I think constructors are really just a special kind of method.)
Overriding allows a subclass to replace the implementation of its parent class.
Overloading allows you to create a different versions of a method that take different parameter lists.

Resources