how to code MyClass<Integer> - java

Below I have 2 classes. The class 'ran' is the main class which will call the 'MyClass' class.
Question: How can I change 'MyClass' so that I can make it work with MyClass<Integer>?
Error: in ran class because I am using <Integer>.
public class ran {
public static void main(String[] args){
MyClass<Integer> m = new MyClass<Integer>();
}
}
public class MyClass{
public MyClass(int n){}
}

the following is a simple usage of generics. T is a template class for which we can use Integer, Float etc.
public class SOJavaApplication {
public static void main(String[] args) {
MyClass<Integer> m = new MyClass<Integer>(5);
m.printScreen();
}
}
//T is the generic type
public class MyClass<T> {
T value; //attribute of type T
public MyClass(T value) {
this.value = value;
}
public void printScreen() {
System.out.println(value);
}
public void add(T n) {
value += n;
}
}

Related

Is there a term for "all primitive types" that can be used as an input to a method?

if I want to make a method that does something to any object that is used as input, I can write a method header that looks like this:
public static void example(Object o){...}
is there a term for "all primitive types" the same way that Object contains all non primitive variables?
I'm not sure if there is a type that encompasses only primitive types, but you can use a wrapper type and throw an error if the input given is not of one of those types.
public static void example(Object o) {
if(!(o instanceof Double)) {
throw new RuntimeException("Error Message");
}
}
This code only checks the Double wrapper type, but you get the idea.
You can use Wrapper type for primitives. Then, they become objects and you can use them wherever you can use Object.
public class Main{
static void print(Object o){
System.out.println(o);
}
public static void main(String[] args) {
Integer i = 5;
Double d = 5.5;
Boolean b = true;
print(i);
print(d);
print(b);
}
}
No, but method overloads are usually how that is accomplished. For example:
// Notice this method is private.
private static void exampleImpl(Object obj) { /* ... */ }
// And these are public, so it is only possible for an outside caller
// to pass (wrapped) primitives to the above method.
public static void example(boolean value) {
exampleImpl(value);
}
public static void example(byte value) {
exampleImpl(value);
}
public static void example(char value) {
exampleImpl(value);
}
public static void example(short value) {
exampleImpl(value);
}
public static void example(int value) {
exampleImpl(value);
}
public static void example(long value) {
exampleImpl(value);
}
public static void example(float value) {
exampleImpl(value);
}
public static void example(double value) {
exampleImpl(value);
}
There is not such thing, but you can use wrapper types with generics. Here is a simple program to demonstrate this:
public class Test{
static <T> void genericMethod(T t){
System.out.println(t);
}
public static void main(String[] args) {
Integer intNum = 10;
Double doubleNum = 36.5;
Boolean aBoolean = true;
Character character = 'a';
genericMethod(intNum);
genericMethod(doubleNum);
genericMethod(aBoolean);
genericMethod(character);
}
}

Why can one call a static method on a type parameter if Java's generics aren't reified?

What's the point of allowing static method invocation on type parameters if Java couldn't be bothered with type reification?
public class a {
interface Foo {
static int getNum() { return 0; }
}
static class FooT implements Foo {
static int getNum() { return 1; }
}
interface A<T extends Foo> {
default int getFooNum() {
return T.getNum();
}
}
static class B implements A<FooT> {}
public static void main(String[] args) {
A p = new B();
// A rational being would expect this to print 1, but being the great
// language that Java is, earthly rationality doesn't hold.
System.out.println(p.getFooNum());
}
}

Downcast reference to runtime-known class

Is there any way by which I can cast a reference of type Object, assuming that the reference could point to any class I defined, to said defined class at runtime?
I've been trying to work it out and the code I came out with is:
public class SomeTestBench {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
myEntity a = new myEntity("Hello Code!");
Receptacle cage = new Receptacle();
cage.injectYourEntity(a);
((cage.itsClass) cage.theEntity).exertExistence();
}
}
That unfortunately does not work, as the class argument to that cast must be static.
Rest of the code:
public class myEntity extends Object{
String warcry;
myEntity(String warcry){
this.warcry = warcry;
}
public void exertExistence(){
System.out.println(this.warcry);
}
}
public class Receptacle {
Object theEntity;
Class itsClass;
public void injectYourEntity(Object it){
this.theEntity = it;
this.itsClass = it.getClass();
}
public void prodIt(){
System.out.println(theEntity.getClass());
}
}
Why don't you just do this using Generics.
public static void main(String[] args) {
myEntity a = new myEntity("Hello Code!");
Receptacle<myEntity> cage = new Receptacle<>();
cage.injectYourEntity(a);
cage.theEntity.exertExistence();
}
//
//That unfortunately does not work, as the class argument to that cast must be static.
//
//Rest of the code:
class myEntity {
String warcry;
myEntity(String warcry){
this.warcry = warcry;
}
public void exertExistence(){
System.out.println(this.warcry);
}
}
class Receptacle<T> {
T theEntity;
public void injectYourEntity(T it){
this.theEntity = it;
}
public void prodIt(){
System.out.println(theEntity.getClass());
}
}
To call a no-arg method named exertExistence() on an object of unknown type, you have three choices:
Use generics. See answer by WJS.
Use reflection:
Receptacle cage = new Receptacle();
cage.injectYourEntity(new myEntity("Hello Code!"));
Method method = cage.itsClass.getMethod("exertExistence", null);
method.invoke(cage.theEntity, null);
Use an interface (recommended):
Receptacle cage = new Receptacle();
cage.injectYourEntity(new myEntity("Hello Code!"));
cage.theEntity.exertExistence();
interface MyInterface {
void exertExistence();
}
class myEntity implements MyInterface {
String warcry;
myEntity(String warcry){
this.warcry = warcry;
}
#Override
public void exertExistence(){
System.out.println(this.warcry);
}
}
class Receptacle {
MyInterface theEntity;
public void injectYourEntity(MyInterface it){
this.theEntity = it;
}
}

How can I call the most specific method using generics?

Having the following example:
public class Test {
public static class A {}
public static void main(String[] args) {
A a = new A();
m1(a);
}
public static <T> void m1(T t) {
// t.getClass().getSimpleName() is A
// t instanceof A is true
m2(t);
}
/* Not called */
public static void m2(A a) {
System.out.println("A");
}
public static void m2(Object o) {
// o.getClass().getSimpleName() is A
// o instanceof A is true
System.out.println("O");
}
}
I don't understand why m2(Object o) is chosen instead of m2(A a). As you can see, when m2(t) is called, t "is an A".
Output:
actual
O
expected
A
How can I use generics for the situation above so that m2(A a) is chosen?
Edit:
I'd like to have a general solution that will work even if I add a type B (similar to A).
...
public static void main(String[] args) {
A a = new A();
m1(a);
B b = new B();
m1(b);
}
...
public static void m2(B b) {
System.out.println("B");
}
...
Output:
actual
O
O
expected
A
B
You have to do:
public static <T extends A> void m1(T t) {
m2(t);
}
Otherwise the compiler cannot infer that the passed parameter is compliant with m2(A a) and with pick m2(Object o) instead.
You are looking for double dispatch which Java does not support. I do not think that generics can help here, but there's the visitor design pattern with which you can emulate it:
public class Test {
public static interface Visitable {
void accept(Visitor visitor);
}
public static class A implements Visitable {
#Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
public static class B implements Visitable {
#Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
public static interface Visitor {
void visit(A a);
void visit(B b);
}
public static class PrintingVisitor implements Visitor {
#Override
public void visit(A a) {
System.out.println("A");
}
#Override
public void visit(B b) {
System.out.println("B");
}
}
public static void main(String[] args) {
Visitable visitable = new A();
m(visitable);
visitable = new B();
m(visitable);
}
public static void m(Visitable visitable) {
visitable.accept(new PrintingVisitor());
}
}

Java: Using different constructors

This is my first day learning java (on my own), so I need some help.
This is my code:
public class java_main {
public static void main(String[] args) {
MyClass my = new MyClass(3,4);
MyClass your = new MyClass();
}
public class MyClass {
public int a,b;
public Myclass(int i, int j) {
a = i;
b = j;
}
public Myclass() {
a = 1;
b = 2;
}
}
}
I'm getting this error:
No enclosing instance of type java_main is accessible. Must qualify the allocation with an enclosing instance of type java_main (e.g. x.new A() where x is an instance of java_main).
Any suggestions? Thanks in advance!!!
The problem you have is that you have enclosed in java_main class MyClass
public class java_main {
public class MyClass {
}
}
Remove the java_main, to get valid result.
public class MyClass {
public static void main(String[] args) {
MyClass my = new MyClass(3,4);
MyClass your = new MyClass();
}
private final int a,b;
public Myclass() {
this(1,2);
}
public Myclass(int a, int b) {
this.a = a;
this.b = b;
}
}
The ussue you have is casued that you have to create first instance of outer class in way to be create instance of inner.
public static void main(String[] args)
{
java_main outer = new java_main();
Myclass my = outer.new Myclass(3,4);
Myclass your = outer.new Myclass();
}
The key word static apply to parts of code that is not part of object it is only enclosed by its path (a method must be in class).
Try to find a tutorial that will guide you.
You could make MyClass public:
public static class MyClass{
...
}
It works ...
public class java_main{
public static void main(String[] args) {
// TODO Auto-generated method stub
Myclass my = new Myclass(3,4);
Myclass your = new Myclass();
System.out.println("keval");
}
}
class Myclass
{
public int a,b;
public Myclass(int i, int j)
{
a = i;
b = j;
}
public Myclass()
{
a = 1;
b = 2;
}
}
change your code to this:
public class java_main {
public static void main(String[] args)
{
Myclass my = new Myclass(3,4);
Myclass your = new Myclass();
}
}
class Myclass
{
public int a,b;
public Myclass(int i, int j)
{
a = i;
b = j;
}
public Myclass()
{
a = 1;
b = 2;
}
}
Just try this,
public class java_main {
public static void main(String[] args) {
MyClass my = new java_main().new MyClass(3, 4);
MyClass your = new java_main().new MyClass();
}
public class MyClass {
public int a, b;
public MyClass(int i, int j) {
a = i;
b = j;
}
public MyClass() {
a = 1;
b = 2;
}
}
}
Better approach is move the public class into separate file
Class name should start with Capital letter as per Java naming standard.
Here, I just created an instance of java_main and by using that instance created an instance for MyClass. This is an approach if you don't want to make MyClass as static inner class.
else make MyClass as static inner class it will work but it depends on use case,
public class java_main {
public static void main(String[] args) {
MyClass my = new java_main().new MyClass(3, 4);
MyClass your = new java_main().new MyClass();
}
public class MyClass {
public int a, b;
public MyClass(int i, int j) {
a = i;
b = j;
}
public MyClass() {
a = 1;
b = 2;
}
}
}
The problem you are having is you cannot reference non-static variables (instances of MyClass) from the static context (main menu in java_main class).
Either you change your MyClass like this,
public static class Myclass
Or take out MyClass out of the java_main class. And remove the public access modifier from the MyClass. Because you cannot have two public classes in the same file.
public class java_main {
public static void main(String[] args)
{
Myclass my = new Myclass(3,4);
Myclass your = new Myclass();
}
}
class Myclass
{
public int a,b;
public Myclass(int i, int j)
{
a = i;
b = j;
}
public Myclass()
{
a = 1;
b = 2;
}
}
Hope this helps for you or someone else.
Cheers!

Categories