How I can make proper use of Generic? - java

public class GenericClass {
public static void main(String... args) {
Hat<Integer> marks = new Hat<Integer>();
marks.tell(4);
Hat<String> apple = new Hat<String>();
apple.tell("apple");
}
}
class Hat<T> {
void tell(T an) {
System.out.println(an + " is good");
}
void tell(String fu) {
System.out.println(fu + " is healthy");
}
}
How is apple.tell("apple") ambiguous? I am trying check how many different ways I can make use of Generic.

apple.tell("apple")
is an String and
void tell(T an) {
System.out.println(an + " is good");
}
T Become String for "apple" so compiler encounter Two String & Overloading is also there so it is ambiguous

Related

Why doesn't making the return type String allow me to return a string in a function

So what I expected this code to display on console was
"hi"
"Ken is a legend"
"forkbomb"
public class ForkBombOnClick {
public static void main(String[] args) {
System.out.println("hi");
ken();
System.out.println("fork bomb");
}
public static String ken() {
return ("ken is a legend");
}
}
But instead it only displays hi and forkbomb. When I change it to public static void ken() then it returns what I wanted the value to be but I was wondering. Why doesn't this current code work?
You need to use the string returned by method ken(); like
System.out.println(ken());
Once a method returns something, you need to get hold of it to use it.
You can also use it like:
String returnValue = ken();
System.out.println(returnValue);
This will also yield same result.
You know the answer yourself!
Why do you use System.out.println? To print on the screen string that you pass to the function.
You do it correctly by System.out.println("hi");, so it prints hi.
Now, you want to print string returned by ken() method. It has string as return type, so you can think of ken(); invocation as a string. Just like hi.
So if you want to print it, you need to use System.out.println and supply result of ken() method to it, just like with other strings: System.out.println(ken());.
You should use return value in print statement which is string as "ken is a legend" .
Your final code should be like this ;
public class ForkBombOnClick {
public static void main(String[] args) {
System.out.println("hi");
System.out.println(ken());
System.out.println("fork bomb");
}
public static String ken() {
return "ken is a legend";
}
}
or more clear version of code ;
public class ForkBombOnClick {
public static void main(String[] args) {
System.out.println("hi" + "\n" + ken() + "\n" + "fork bomb");
}
public static String ken() {
return "ken is a legend";
}
}
In this System.out.println("hi" + "\n" + ken() + "\n" + "fork bomb");
\n refers to newline.

Anonymous inner class example validity concern

I was trying to review some of the Java language using a spark chart I had once bought. Regarding the use of anonymous inner classes they give this example :
Dice rollDice() {
return new Dice() {
int number = (int)( Math.random() * 6 ) + 1;
};
}
Problem is, I do not see how this would work, and can not get the compiler to accept it as a method within another class. The compiler complains about each reference to Dice "symbol can not be found."
Am I not understanding their example correctly or is this completely invalid code? Thanks in advance!
p.s. if this is working code, could someone provide me with an example of how it can be used?
Edit: I have found something that finally makes sense
The syntax for an anonymous inner class is shown below
new SuperClassName/InterfaceName() {
// Implement or override methods in superclass or interface
// Other methods if necessary
}
This above code is passed to a method that takes an instance of Superclass or completely implements the Interface. For instance, a method that has an EventHandlerparameter and we have not already defined a class that implements the handle(ActionEvent e) method.
enlargeButton.setOnAction(
new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
circlePane.enlarge();
}
});
In this way, it will truly be anonymous. I think the example given in Java's own tutorial to be very poor.
It looks like you've mostly answered your own question and you will probably want to go through some full tutorial or documentation to understand things fully, but here are some answers to your immediate questions.
Your first sample code wont compile until you have a Dice class or interface you can extend. So as an example you can get this code to compile:
class Dicey {
interface Dice {
}
Dice rollDice() {
return new Dice() {
int number = (int) (Math.random() * 6) + 1;
};
}
public static void main(String... none) {
Dice dice = new Dicey().rollDice();
// dice.number; <-- not available
}
}
Now you can do this, but as you suspect this is not a very useful things to do (for a few reasons) but the biggest problem is that after you create this anonymous instance there isn't really a way to get to the .number member.
More usually you would have an anonymous subclass implement some methods on the interface, so that you can actually do something with it. So for example
class HelloAnonymous {
interface Hello {
String say();
}
Hello hello(String world) {
return new Hello() {
public String say() {
return world;
}
};
}
public static void main(String... none) {
System.out.println(new HelloAnonymous().hello("world").say());
// prints 'world'
}
}
gives you a way of making fantastically useful Hello objects that can say something. Having said all this, writing anonymous inner classes is fairly old school because functional interfaces now largely replace the need for them. So in this example you could have:
class HelloAnonymous {
#FunctionalInterface
interface Hello {
String say();
}
// old school
Hello hello(String world) {
return new Hello() {
public String say() {
return world;
}
};
}
// with lambda notation
Hello alsoHello(String world) {
return () -> {
return world;
};
}
public static void main(String... none) {
System.out.println(new HelloAnonymous().hello("world").say());
System.out.println(new HelloAnonymous().alsoHello("world").say());
}
}
since I don't know about 'Dice' class I cannot write same method but I try some thing similar to that. It compile and work can access 'number' variable by using reflection. My opinion is it is not very useful. Following is my code:
public class TestClass {
public static void main(String a[]){
TestClass aClass = rollDice();
try {
System.out.println("value of number : " + aClass.getClass().getDeclaredField("number").getInt(aClass));
}
catch (NoSuchFieldException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
}
static TestClass rollDice() {
return new TestClass() {
int number = (int) (Math.random() * 6) + 1;
};
}
}
That example is extremely broken. Throw that source away. Try this:
import java.util.Random;
public class DieFactory {
interface Die { int roll(); }
static Die create(long seed) {
Random random = new Random(seed);
return new Die() {
#Override
public int roll() {
return random.nextInt(6) + 1;
}
};
}
// Now you can roll 2 dice pretty easily.
public static void main(String [] args) {
DieFactory.Die die1 = DieFactory.create(42);
DieFactory.Die die2 = DieFactory.create(24);
for (int i = 0; i < 40; i++) {
System.out.println(die1.roll() + die2.roll());
}
}
}
Incidentally, the word "dice" is plural for the singular "die."

Cannot understand the difference between static and non-static variables in Java. Can anyone help please? [duplicate]

This question already has answers here:
What is the difference between a static method and a non-static method?
(13 answers)
Closed 5 years ago.
In java, i am trying to understand the difference between static and non-static objects and variables like this.
Code with static object:
package abc;
public class StaticUsage {
public static StaticUsage propfile;
public static void main(String[] args) {
checkifPropertiesFileisnull();
checkifPropertiesFileisnull();
checkifPropertiesFileisnotnull();
/*stu.checkifPropertiesFileisnull();*/
}
private static void checkifPropertiesFileisnotnull() {
if(propfile==null) {
System.out.println("Propfile is " + propfile);
propfile = new StaticUsage();
}
else {
System.out.println("Propfile value is " + propfile);
}
}
private static void checkifPropertiesFileisnull() {
if(propfile==null) {
System.out.println("Propfile is " + propfile);
propfile = new StaticUsage();
}
else {
System.out.println("Propfile value is " + propfile);
}
}
}
Code with non-static object:
package abc;
public class StaticUsage {
public StaticUsage propfile;
public static void main(String[] args) {
StaticUsage stu = new StaticUsage();
stu.checkifPropertiesFileisnull();
stu.checkifPropertiesFileisnull();
stu.checkifPropertiesFileisnotnull();
/*stu.checkifPropertiesFileisnull();*/
}
private void checkifPropertiesFileisnotnull() {
if(propfile==null) {
System.out.println("Propfile is " + propfile);
propfile = new StaticUsage();
}
else {
System.out.println("Propfile value is " + propfile);
}
}
private void checkifPropertiesFileisnull() {
if(propfile==null) {
System.out.println("Propfile is " + propfile);
propfile = new StaticUsage();
}
else {
System.out.println("Propfile value is " + propfile);
}
}
}
However, in both cases i am getting output as the below:
Propfile is null
Propfile value is abc.StaticUsage#15db9742
Propfile value is abc.StaticUsage#15db9742
I have heard that for static objects, it is shared throughout the instance of the class. So, i am getting the value for the first time as null, and the rest not null. But, then why for non-static objects, i am getting the same value? The value for the first method call should go to heap according to me, and then at the time of calling the second method, it should be again showing as null.
Can anyone please clear me the confusion?
Static properties belong to the Class whereas instance variables belong to the particular object instance. You should take a read through this: https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

Automated or shorcut for method access logging

This may come across as a relatively stupid question, but I'm getting tired of having to hard code statements such as:
private void doStuff(){
System.out.println(this.getClass().getName().toString()+ someText);{...};}
every time I want to
So I decided to implement an external method which writes in the output stream whenever I decide I need something written there such as:.
public static void println(Object obj, String s) {
System.out.println(obj.getClass().getName() + " > " + s);
}
So the question is, Is there a way to automatically set the value of the 's' variable in the method above to always default to "initialized" when writing source code (using TAB for code completion e.g. Netbeans)?
Many thanks in advance.
Use varargs as the second method parameter. This will also allow you to pass multiple debug statements.
public class Logger {
public static void main(String[] args) {
String test = "Test";
println(test);
println(test, "This is a test");
}
public static void println(Object obj, String...vargs) {
String defaultValue = "initialized";
if(vargs.length == 0){
System.out.println(obj.getClass().getName() + " > " + defaultValue);
}else{
for(String x: vargs){
System.out.println(obj.getClass().getName() + " > " + x);
}
}
}
}
Why don't you just overload the method with a default value?
public static void println(Object obj) {
println(obj, "Initalized");
}
public static void println(Object obj, String s) {
System.out.println(obj.getClass().getName() + " > " + s);
}

Java, clever way to replace "if not null" statement?

I have a Vector full of longs.
I would like to be able to always call getFirstElement() on a Vector and then perform an action, let's say addToOtherVector(). I want to be able to not worry whether or not there is actually a value to return from my original vector. I think I could do it by overriding addToOtherVector() like so:
//Code to be called when my first vector is not empty
public void addToOtherVector(long s){
othervector.add(s);
}
//Code to be called when my first vector IS empty
public void addToOtherVector(something???){
//does nothing
}
but I'm not sure what i need to do for the something, as it won't accept null as a parameter?
The reason I am doing this is because I don't wish to have to check the size of the vector each time I try to retrieve
Just override the method with a base class. Since Number is the base class to Long, Integer, etc. just use that one :
//Code to be called when my first vector is not empty
public void addToOtherVector(long s){
othervector.add(s);
}
//Code to be called when my first vector IS empty
public void addToOtherVector(Number s){
if (s == null) {
return;
}
othervector.add(((Number) s).longValue());
}
import java.util.Vector;
public class Main {
static Vector otherVector = new Vector();
public static void main(String[] args) {
Vector originalVector = new Vector();
originalVector.add(1);
originalVector.add(null);
originalVector.add(2);
for (Object obj : originalVector) {
addToOtherVector(obj);
}
}
public static void addToOtherVector(long s) {
otherVector.add(s);
System.out.println("adding " + s + " to vector");
}
public static void addToOtherVector(Object obj) {
System.out.println("not adding " + obj + " to vector");
}
}

Categories