the cause of overloading a constructors in java - constructor

So I just can't seem to understand the problem of overloading. I know it is caused by constructors sharing the same parameters; but do that have to be exactly the same or will the overload happen if they share one common parameter, or even they if one had three parameters but shares two with another?

Not sure what you are asking here.
But Overloading is not only for Constructors. That can be for other methods too.
Here are the rules (My). You can have same method name, but the parameters should be different.
Example: Constructor Overloading
public Car()
{
}
private Car(int speed, int maxSpeed)
{
//...
}
public Car(String make, String model)
{
//...
}
This is overloading.
But below is illegal with the above constructors.
public Car(String color, String make)
{
//...
}
Because the JVM wouldn't be able to distinguish the (String make, String model) & (String color, String make) Constructors. Therefore the rule is, parameters should be different (Types and/or the number of parameters).
Again Remember:
public void printNames(String name1, String name2)
public void printNames(String x, String y)
This is not overloading and even the compiler wouldn't let you do it.

A java class can contain two or more methods with the same name, provided that those methods accept different parameters. That is called overloading. When you create overloaded methods every method must have a unique signature.

Related

Understanding Factory constructor code example - Dart

I have some niggling questions about factory constructors example mentioned here (https://www.dartlang.org/guides/language/language-tour#factory-constructors).
I am aware of only three types of constructors on a basic level - default, named and parameterised.
Why should I use factory at all for this example?
Is that a named constructor which is being used? and why?
tl;dr Use a factory in situations where you don't necessarily want to return a new instance of the class itself. Use cases:
the constructor is expensive, so you want to return an existing instance - if possible - instead of creating a new one;
you only ever want to create one instance of a class (the singleton pattern);
you want to return a subclass instance instead of the class itself.
Explanation
A Dart class may have generative constructors or factory constructors. A generative constructor is a function that always returns a new instance of the class. Because of this, it does not utilize the return keyword. A common generative constructor is of the form:
class Person {
String name;
String country;
// unnamed generative constructor
Person(this.name, this.country);
}
var p = Person("...") // returns a new instance of the Person class
A factory constructor has looser constraints than a generative constructor. The factory need only return an instance that is the same type as the class or that implements its methods (ie satisfies its interface). This could be a new instance of the class, but could also be an existing instance of the class or a new/existing instance of a subclass (which will necessarily have the same methods as the parent). A factory can use control flow to determine what object to return, and must utilize the return keyword. In order for a factory to return a new class instance, it must first call a generative constructor.
In your example, the unnamed factory constructor first reads from a Map property called _cache (which, because it is Static, is stored at the class level and therefore independent of any instance variable). If an instance variable already exists, it is returned. Otherwise, a new instance is generated by calling the named generative constructor Logger._internal. This value is cached and then returned. Because the generative constructor takes only a name parameter, the mute property will always be initialized to false, but can be changed with the default setter:
var log = Logger("...");
log.mute = true;
log.log(...); // will not print
The term factory alludes to the Factory Pattern, which is all about allowing a constructor to return a subclass instance (instead of a class instance) based on the arguments supplied. A good example of this use case in Dart is the abstract HTML Element class, which defines dozens of named factory constructor functions returning different subclasses. For example, Element.div() and Element.li() return <div> and <li> elements, respectively.
In this caching application, I find "factory" a bit of a misnomer since its purpose is to avoid calls to the generative constructor, and I think of real-world factories as inherently generative. Perhaps a more suitable term here would be "warehouse": if an item is already available, pull it off the shelf and deliver it. If not, call for a new one.
How does all this relate to named constructors? Generative and factory constructors can both be either unnamed or named:
...
// named generative
// delegates to the default generative constructor
Person.greek(String name) : this(name, "Greece");
// named factory
factory Person.greek(String name) {
return Greek(name);
}
}
class Greek extends Person {
Greek(String name) : super(name, "Greece");
}
There is not much difference between a static method and a factory constructor.
For a factory constructor the return type is fixed to the type of the class while for a static method you can provide your own return type.
A factory constructor can be invoked with new, but that became mostly irrelevant with optional new in Dart 2.
There are other features like redirects rather rarely used that are supported for (factory) constructors but not for static methods.
It is probably still good practice to use a factory constructor to create instances of classes instead of static methods to make the purpose of object creation more obvious.
This is the reason a factory constructor is used in the example you posted and perhaps because the code was originally written in Dart 1 where it allowed to create a logger instance with new like with any other class.
Yes this is a named constructor and the prefix _ makes it a private named constructor. Only named constructors can be made private because otherwise there would be no place to add the _ prefix.
It is used to prevent instance creation from anywhere else than from the public factory constructor. This way it is ensured there can't be more than one Logger instance in your application.
The factory constructor only creates an instance the first time, and for subsequent calls always returns the previously created instance.
Complementing Dave's answer, this code shows a clear example when use factory to return a parent related class.
Take a look a this code from https://codelabs.developers.google.com/codelabs/from-java-to-dart/#3
You can run this code here. https://dartpad.dartlang.org/63e040a3fd682e191af40f6427eaf9ef
Make some changes in order to learn how it would work in certain situations, like singletons.
import 'dart:math';
abstract class Shape {
factory Shape(String type) {
if (type == 'circle') return Circle(2);
if (type == 'square') return Square(2);
// To trigger exception, don't implement a check for 'triangle'.
throw 'Can\'t create $type.';
}
num get area;
}
class Circle implements Shape {
final num radius;
Circle(this.radius);
num get area => pi * pow(radius, 2);
}
class Square implements Shape {
final num side;
Square(this.side);
num get area => pow(side, 2);
}
class Triangle implements Shape {
final num side;
Triangle(this.side);
num get area => pow(side, 2) / 2;
}
main() {
try {
print(Shape('circle').area);
print(Shape('square').area);
print(Shape('triangle').area);
} catch (err) {
print(err);
}
}
In addition to the other answers, also consider the order of instantiating objects and when the instance is created:
In normal constructor, an instance gets created and the final variables get instantiated with the initializer list. This is why there's no return statement. The instance to return is already fixed, when executing the constructor!
In a factory constructor, the instance to return is decided by the method. That's why it needs a return statement and why it'll usually call a normal constructor in at least one path.
So a factory does nothing different than a static method could do (in other languages often called getInstance()), except you cannot overload the constructor with a static method but you can with a factory method. I.e. factory methods are a way to hide the fact that the user of your class is not calling a constructor but a static method:
// C++
MyCoolService.getInstance()
// Dart
MyCoolService()

How to check that a List contains only certain unrelated class types using junit's assertThat?

Would appreciate some help with hamcrest and junit matchers... :)
I'm using junit-4.11.jar and hamcrest-core-1.3.jar on Eclipse Kepler with sun's jdk 1.6.0_30.
I have a class that holds an instance of any unknown type like so:
class UnknownClassHolder {
private Class<?> clazz;
public Class<?> getClazz() {
return clazz;
}
public void setClazz(Class<?> clazz) {
this.clazz = clazz;
}
}
clazz can be any class.
I want to my junit test to be something like this:
class UnknownClassHolderTest {
#Test
public void test() {
ArrayList<UnknownClassHolder> list = new ArrayList<UnknownClassHolder>();
UnknownClassHolder x = new UnknownClassHolder();
//lets add an Integer
x.setClazz(Integer.class);
list.add(x);
UnknownClassHolder y = new UnknownClassHolder();
//lets add a vector
y.setClazz(Vector.class);
list.add(y);
//now check that we added an Integer or a Vector using assertThat
for (UnknownClassHolder u: list) {
assertThat(u.getClazz(), anyOf(isA(Integer.class), isA(Vector.class))));
}
}
}
Junit's assertThat doesn't like this. It doesn't compile due to Integer & Vector Types not being related to each other via sub/super classes:
The method assertThat(T, Matcher<? super T>) in the type Assert is not applicable for the arguments (Class<capture#1-of ?>, AnyOf<Vector>)
Is there a more succinct way to do this other than:
assertThat(u.getClazz().getName(), either(is(Integer.class.getName())).or(is(Vector.class.getName())));
Is there a particular reason for using Matcher<? super T> rather than Matcher<?> in the org.hamcrest.MatcherAssert.assertThat(...) method?
Thanks.
First, you should be using is instead of isA since you're asserting that one class equals another. isA is for testing that an object is an instance of some class. Second, the only thing I can make work is forcing the compiler to see these as raw Objects.
assertThat(u.getClazz(), anyOf(is((Object) Integer.class), is((Object) Vector.class)));

List of OO languages where object immutability can be compiler enforced

Can anyone give me a list of languages where class immutability can be compiler enforced and tested easily ?
I need to be able to do something like:
class immutable Person {
private String name = "Jhon"; // lets say the String is mutable
public Person(String name) {
this.name = name; // ok
}
public void setName(String newName) {
this.name = newName; // does not compile
}
public void getName() {
return this.name; //returns reference through which name can't be mutated
}
private void testImmutability() {
getName().setFirstChar('a'); // does not compile
}
}
EDIT:
For a little more clarification, see here.
Functional programming languages like OCAML, Haskell, and Erlang.
F# and Scala both have the ability to created compiler-enforced immutable types (i.e. classes).
The following shows the basics in F#...
// using records is the easiest approach (but there are others)
type Person = { Name:string; Age:int; }
let p = { Person.Name="Paul";Age=31; }
// the next line throws a compiler error
p.Name <- "Paulmichael"
Here's the equivalent Scala. Note that you can still make mutable objects by using var instead of val.
class Person(val name: String, val age: Int)
val p = new Person("Paul", 31)
// the next line throws a compiler error
p.name = "Paulmichael"
Joe-E
From the language spec
3.4 Immutable Types
A type T is immutable if and only if it implements
the marker interface org.joe_e.Immutable according to the overlay
type system. The (empty) org.joe_e.Immutable interface must be provided
by the Joe-E implementation. The
intuition behind an immutable object
is that such an object cannot be
changed (mutated) in any observable
way, nor can any objects reachable by
following the elds of the immutable
object. The contents of an immutable
objects' elds and any objects
reachable from an immutable object
must not change once the object is
constructed. With the exception of
library classes explicitly deemed to
implement Immutable, an immutable
class must satisfy additional
linguistic restrictions enforced by
the verier (x4.4) to ensure this
property. Library classes that cannot
be automatically verified and are
deemed immutable must be carefully
manually veried to expose no
possibility for modication of their
contents. Note that immutability does
not place any restrictions on any
local variables dened within the
immutable class. It also says nothing
about the mutability of the arguments
passed to methods. It only applies to
the values stored in and objects
reachable from the immutable class's
elds
It also introduces useful notions of powerless, and selfless types.
The D (version D2) programming language has immutability. It has OOP, but immutability is rather a concept from functional pl. There it's called purity.

Proper usage of "this." keyword in C#?

I'm working through the book Head First C# (and it's going well so far), but I'm having a lot of trouble wrapping my head around the syntax involved with using the "this." keyword.
Conceptually, I get that I'm supposed to use it to avoid having a parameter mask a field of the same name, but I'm having trouble actually tracking it through their examples (also, they don't seem to have a section dedicated to that particular keyword, they just explain it and start using it in their examples).
Does anyone have any good rules of thumb they follow when applying "this."? Or any tutorials online that explain it in a different way that Head First C#?
Thanks!
Personally I only use it when I have to which is:
Constructor chaining:
public Foo(int x) : this(x, null)
{
}
public Foo(int x, string name)
{
...
}
Copying from a parameter name into a field (not as common in C# as in Java, as you'd usually use a property - but common in constructors)
public void SetName(string name)
{
// Just "name = name" would be no-op; within this method,
// "name" refers to the parameter, not the field
this.name = name;
}
Referring to this object without any members involved:
Console.WriteLine(this);
Declaring an extension method:
public static TimeSpan Days(this int days)
{
return TimeSpan.FromDays(days);
}
Some other people always use it (e.g. for other method calls) - personally I find that clutters things up a bit.
StyleCop's default coding style enforces the following rule:
A1101: The call to {method or property
name} must begin with the 'this.'
prefix to indicate that the item is a
member of the class.
Which means that every method, field, property that belongs to the current class will be prefixed by this. I was initially resistant to this rule, which makes your code more verbose, but it has grown on me since, as it makes the code pretty clear. This thread discusses the question.
I write this. if and only if it enhances readability, for example, when implementing a Comparable interface (Java, but the idea is the same):
public void compareTo(MyClass other) {
if (this.someField > other.someField) return 1;
if (this.someField < other.someField) return -1;
return 0;
}
As to parameter shadowing (e.g. in constructors): I usually give those a shorter name of the corresponding field, such as:
class Rect {
private int width, height;
public Rect(int w, int h) {
width = w;
height = h;
}
}
Basically, this gives you a reference to the current object. You can use it to access members on the object, or to pass the current object as parameters into other methods.
It is entirely unnecessary in almost all cases to place it before accessing member variables or method calls, although some style guidelines recommend it for various reasons.
Personally, I make sure I name my member variables to be clearly different from my parameters to avoid ever having to use 'this.'. For example:
private String _someData;
public String SomeData
{
get{return _someData;}
set{_someData = value;}
}
It's very much an individual preference though, and some people will recommend that you name the property and member variable the same (just case difference - 'someData' and 'SomeData') and use the this keyword when accessing the private member to indicate the difference.
So as for a rule of thumb - Avoid using it. If you find yourself using it to distinguish between local/parameters variables and member variables then rename one of them so you don't have to use 'this'.
The cases where I would use it are multiple constructors, passing a reference to other methods and in extension methods. (See Jon's answer for examples)
If you have a method inside a class which uses same class's fields, you can use this.
public class FullName
{
public string fn { set; get; }
public string sn { set; get; }
//overriding Equals method
public override bool Equals(object obj)
{
if (!(obj is FullName))
return false;
if (obj == null)
return false;
return this.fn == ((FullName)obj).fn &&
this.sn == ((FullName)obj).sn;
}
//overriding GetHashCode
public override int GetHashCode()
{
return this.fn.GetHashCode() ^ this.sn.GetHashCode();
}
}

Should a class ever have static and non-static members

I'm trying to figure out when it would be appropriate for a class to have both static and non-static functions. AKA:
$obj = new ClassA;
$obj->doOOPStuff();
$something = ClassA::doStaticStuff();
Note: This example is done in PHP, however the question is language agnostic .
It seems that if you have a class that is meant to be instantiated, any functions that can be called statically, most likely belong in another class.
Is there any viable cases where I would have a class that used static AND non-static members?
One example: when Creation has to happen in a specific way.
class Foo {
public:
static Foo* Create(...params...);
private:
Foo();
};
Consider String class in .NET. It contains a non-static Split method which breaks some instance into a string[] and a static Join method, which takes a string[] and transform it into a string again.
A static method is applicable when you don't need to keep any state. So Math.Sin() just depends on its parameters and, given same parameters, output will always be the same. A non-static method can have different behavior is called multiple times, as it can keep a internal state.
If the functionality provided by static methods is relevant to that class and its objects, why not. It is pretty common.
Static method are most often factory methods
public class MyClass {
public static MyClass createMyClass(int a, double b) {..}
public static MyClass createSubclassOfMyClass(int c, boolean cond) {..}
public int calculateThis();
public double calculateThat();
}
Another use is to access some property that is logically bound that that class, but not separately to instances. For example - a cache:
(Note - of course synchronization should be taken into account in this example)
public class MyClass {
public static final Cache cache = new Cache();
public static void putInCacheIfNeeded(Object obj) {..}
public static void replaceInCache(Object obj) {..}
public void doSomethingCacheDependend(Object obj) {
if (something) {
MyClass.putInCacheIfNeeded(obj);
} else {
MyClass.replaceInCache(obj);
}
}
}
(Java language for the examples)
Imagine your constructor has two overloads that both are strings:
public class XmlDocument
{
public static XmlDocument CreateFromFile(string filePath);
public static XmlDocument CreateFromXml(string xml);
}
The static function can provide meaningful name to the constructor.
$dialog = DialogFoo::createOpenDialog();
$dialog = DialogFoo::createDocumentOpenDialog();
$dialog = DialogFoo::createImageOpenDialog();
It could also be used to enforce Singleton pattern.
$dialog = DialogFoo::getInstance()
Static class members are most useful where everything must either be in an object or be in a global scope; they are less useful in a language such as Python that supports module-level scopes.
I use static methods to instantiate new objects when I dont want the to give access to the constructor. I ensure that any necessary preconditions are carried out on the class before creating and object. In this example I have a counter to return how many objects are created, if I have 10 objects I prevent any more from being instantiated.
class foo {
private:
static int count;
foo() {}
public:
static foo bar() {
count++;
if (count<=10){
return new foo;
} else {
return null;
}
Let's assume a class has instance methods, here are some good use case for having static methods too:
For static utility methods
Such methods apply to any instance, for example String.format(String, Object...) in Java.
Use them when you don't want to create a specific instance for the job.
For static factory methods
Factory methods are methods that simply instantiate objects like the getInstance() and valueOf() methods in the Java API. getInstance() is the conventional instantiation method in singletons while valueOf() are often type-conversion methods, like in String.valueOf(int).
Use them to improve performance via object-caching, in interface-based frameworks (like the Collections Framework in Java) where you may want to return a subtype, to implement singletons (cough).
In general, static functions produce functionality highly related to class itself. It may be some helper functions, factory methods etc. In this case all functionality contains in one place, it correspond to DRY principle, increases cohesion and reduces coupling.