class Foo {
static int x = 5;
}
public class Bar {
public static void main(String[] args) {
Bar bar = new Bar();
bar.run();
}
public void run() {
this.what(Foo);
}
public void what(Class<Foo> cls) {
System.out.println(cls.x);
}
}
``` I have this code and (coming from Python) I expected this to print '5', but this does not seem to work in Java and im not sure how I would make this work, I think its pretty clear what im trying to do from the code but if not please ask me its hard to put this in words tbh
#Some basic java help
337 messages · Page 1 of 1 (latest)
⌛ This post has been reserved for your question.
Hey @echo token! Please use
/closeor theClose Postbutton above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
I basically just wanna pass the class as a param and access static variables from that class
I assumed this would be possible since they are static
classes, types, functions aren't first-class members in java. you can't pass them around.
Class is used for reflection, it doesn't do what you want it to. you could technically access x from it, but again, that's reflection, it's not a mechanic of java.
in a python equivalent, Foo would still not be used as a class, but as an arbitrary object.
try reading about oop
Yeah I understand OOP
Context for my use case: im not able to create a class instance, I need to access some static variables from said class to create an instance
I understand here you could use Foo.x but in my use case Foo is a superclass that’s a shell for a lot of other classes
well.. you can just access those static variables from said class directly
so you want to inherit from Foo?
Foo inside of Class<Foo> would be a subclass of Foo
it wouldn't
Are there any alternatives for what I’m trying to do
/run
class X { public static void main(String[] args) {
Class<Object> cls = String.class;
}}
@merry edge I only received java(15.0.2) error output
file0.code.java:2: error: incompatible types: Class<String> cannot be converted to Class<Object>
Class<Object> cls = String.class;
^
1 error
error: compilation failed
i have no idea what you're trying to do.
I can share a shell of my actual use case in a couple minutes
honestly, it sounds like xyproblem
please do, your description here is pretty vague
Like I said kind of hard to explain
I can share working python code aswell of the thing I’m trying to do
to me, it sounds like you're trying to design something dynamic, which python would do well, but java is a static type system, so it just falls apart in java
so it's an issue of design
Not at my pc atm tho, give me 15 minutes
sure
(please strip it down to just the relevant part though)
from typing import (
ClassVar,
)
class Super:
x: ClassVar[int]
class Sub1(Super):
x = 1
class Sub2(Super):
x = 2
class Sub3(Super):
x = 3
def foo(sub: type[Super]) -> None:
print(sub.x)
foo(Sub1)
foo(Sub2)
foo(Sub3)
@merry edge I guess that would be it
Id have a subclass, any of Sub1, Sub2, Sub3 and when I would call a function I would be able to get static variables from said class
why do Subn have to be classes there to begin with?
this would print 1 2 3 as expected
well they have their use case but thats not really relevant
why can't you just
class X:
def __init__(self, x: int):
self.x = x;
sub1 = X(1)
# ...
it very much is relevant
what you use something for kinda heavily influences the design.
this is not what I need
its a class var
never would change
it is a class which ALWAYS has some variables, in my example x and an init with other params that can differ
x would never chnage
python doesn't have a way to denote things that don't change
thats why I type hinted it as a class var
well not during runtime but typing.ClassVar is for that
if you have multiple classes each with their own class var, what's the difference between that and multiple instances each with their own instance var?
honestly i cant explain it better than how I have
you didn't show that in your example, so i don't know what you mean by that. do you mean that you're trying to use Super as an interface?
I mean sort of but as I understood interfaces can only define method shells
don't go there yet; we're still talking about design, not specifically java.
you stripped too much out of your description, you left out the motivation behind your python implementation
again; why can't they be instances?
because to create said instance I would need to use said x
which differs per sub class
a hashmap would work but I think this would be way cleaner
my acutal use case:
class Animal {
public static int number;
public static HomeType desiredHomeType;
public static Diet diet;
public final String name;
public final Home home;
/**
* .
*/
public Animal(
String name,
Home home
) {
this.name = name;
this.home = home;
}
public static final Class<Animal> classFromNumber(int number) {
return Animal.class;
}
}
final class Lion extends Animal {
public final int number = 1;
public final HomeType desiredHomeType = HomeType.BOTH;
public final Diet diet = new Diet(
DietType.CARNIVORE
);
public Lion(
String name,
Home home
) {
super(name, home);
}
}
final class Tiger extends Animal {
public final int number = 2;
public final HomeType desiredHomeType = HomeType.BOTH;
public final Diet diet = new Diet(
DietType.CARNIVORE
);
public Tiger(
String name,
Home home
) {
super(name, home);
}
}
final class Leopard extends Animal {
public final int number = 3;
public final HomeType desiredHomeType = HomeType.BOTH;
public final Diet diet = new Diet(
DietType.CARNIVORE
);
public Leopard(
String name,
Home home
) {
super(name, home);
}
}```
there are a lot more animals, its for homework
that's... not what im talking about though
no, the instance itself defines x.
instead of having Subn extend Super, they can be instances of Super
I need to use desiredHomeType to check if there is a valid Home
like i showed here
in that example they can but thats not my point
in here they cannot be instances
then you made a bad example that doesn't show your case well
because a Lion would never have a differnent Diet
and I dont wanna have to pass that in as a param when I create a Lion
i mean, they could. seriously.
I dont really see how
I made a minimal example like you asked lol
yeah, but you wouldn't have a definition of lion there. the definition of lion comes with the definition of the diet
no, again, you stripped out too much
"minimal" is not least code, minimal is least code to explain your issue
honestly if you have a better way to do it wiht my actual use case (the java code I just sent) im all ears
if you strip out a part that causes problems, how are we supposed to identify the problems we can't see?
the python code worked fine
perfectly as expected
I wanna (sort of) replicate that in java
i'll get to that in a sec; but i think you are misunderstanding how instances work
Animal lion = new Animal(DietType.Carnivore); // lion will always have the same diet
python OOP is pretty far from any other language's OOP.
I dont want the user to have to specify that a lion will have a carnivore diet
and the user doesn't have to do that.
beacuse frankly a Lion in my code will always have that
just like the user doesn't have to define the class Lion. you can do that for them.
then you can define it to be such.
well thats what im trying to do
and i just told you you can do it with no issue
just that it wouldn't be constructible as its own class, since it wouldn't be a class there.
youve told me but not shown me
i literally did show you
I have this function
public boolean addAnimal(
Class<Animal> animalClass,
String name,
HomeType homeType
) {
if (this.nameExists(name)) {
return false;
}
Home home = this.findHome(animalClass, homeType);
if (home == null) {
return false;
}
Animal animal = new Animal(name, home);
home.animals.add(animal);
return true;
}```
which will TRY to add an animal
but will return false early if its not allowed
to hceck if there is a home for the animal, I need to access Animal.desiredHomeType
but not for the actual Animal
but for the subclass class passed into AddAnimal
and that's why i asked if it was for defining an interface.
dude you aren't listening to me
I am
is this defining an interface? I thought interface you meant an actual interface
interface Foo {}```
again; talking about design. the class Super in your python code defines something which subclasses have to implement. that's an interface.
yeah well sort of then I guess
but I thought in Java interfaces were solely for methods
which mine is not
mine would be solely for variables
they are
and it would need a constructor aswell
yeah well dont need that
...no, you're construing ideas
they are hard coded variables which will never change
methods... can do that.
they don't need to be variables. they just need to be accessible
although, i think you could make them variables with an abstract class.
let me reiterate what i said before (which isn't the fix to your problem, but just an explanation) {
under the premise that the separate Sub1, etc don't actually have to be classes (since that was omitted at first)
from some superclass, you can either:
make extending classes, where each has a class variable. 1 new thing - 1 new value. (which you did.)
make instances, where each has an instance variable. 1 new thing - 1 new value. (which i was trying to explain was possible.)
}
so about your actual problem;
make instances, where each has an instance variable. 1 new thing - 1 new value. (which i was trying to explain was possible.)
I know its possible but I would like to refrain from using this
use case as per the homework assignment:
I get input as a number
1-7
....you were completely denying it before.
based on that, I create an Animal class
uhhhhh no?
I meant in my use case its not possible
possible as in not allowed by the homework assignment
you did not describe your use case accurately; i was trying to explain that without the part you left out, it was possible.
but we're just going in circles there so whatever
what im trying to do with this number 1-7:
some method that returns the actual class of the animal corresponding to the number:
that is: Lion, Tiger, Leopard etc. etc.
ok, that part is not possible. at least not cleanly.
then I call addAnimal with this class and a home
home I also get with a number from input
ok that's far besides the point now
so the core of your problem is;
you need to define a class that represents a type of animal, and specifically a class because it needs to be instantiated with a home/name.
each type of animal should have its own unchanging fields, namely diet and desiredHomeType.
am i understanding that correctly?
yes
what I was trying to do, in python terms because am way more familiar with said syntax:
i have an implementation idea in mind, but give me a sec to see what other stuff is possible.
def get_animal_class_based_on_number(number: int) -> type[Animal]: # Never actually type[Animal], always type of a subclass of Animal
...
class HomeType(Enum):
doesnt matter
def get_home_type_based_on_number(number: int) -> HomeType:
...
def add_animal(
animal_class: type[Animal],
home_type: HomeType,
name_of_animal: str,
):
actual logic to add the animal
n1 = ...
n2 = ...
animal_cls = get_animal_class_based_on_number(n1)
home_type = get_home_type_based_on_number(n2)
add_animal(animal_cls, home_type, 'some name')
alright thanks
If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
lol does it have some filter that checks for the word thanks
thanks
also I timer I suppose
on cooldown i guess
ok so your python design doesn't work in normal OOP at all it seems, or at least it isn't exactly logically sound within typical OOP
but it's working in python since python is insanely dynamic
think of this; for any arbitrary instance of Animal, should diet be constant?
yes
every species of animal eats the same diet
all these variables will never cahnge
ok i phrased that horribly sec
should I make those final aswell or is that bad?
Animal a; Diet d;
a = getRandomAnimal();
d = a.diet;
a = getRandomAnimal();
d == a.diet ?
should any 2 arbitrary animals always have the same diet
so should Animal.diet be static?
but it does change, across species. you just said so.
no I mean like
every species has a differnet diet
which never changes
after the classes are defined, they never change
not sure if java caches those variables but in my understanding they get cached and should remain the same forever
ok but say i have an animal a of species A
and an animal b of species B
and they have different diets
they're both animals. do arbitrary animals have different diets?
like I said animals from different species can have different diets
animals from the same species have the same diet
it does not change
a static Animal.diet means that every single animal shares the same diet
so that's a contradiction
youre looking at my code
that's what it means to be static.
look what im saying
im looking at both your code and your words
im not very familiar with java, tahts why im asking for help
for the third time:
every animal has the SAME DIET as animals that have the SAME SPECIES
you're getting mixed up about every animal of a given species having the same diet, and that diet being static on the animal class
if an animal is not of the same species it does not have to have the same diet
sometimes they do, but doenst have to
dude. i understand. im trying to poke you in the direction of understanding
of the same species.
Animal, is not for the same species
diet and desiredHomeType should not be static.
there, i said it.
which doesn't work.
am too unfamiliar with static to fully understand why not tbh
I thought static meant
Class.var
instead of Class().var
so it would be a ClassVar instead of a variables of an instance
that's the syntactic (how you use it) meaning, not the semantic (what it means) meaning
oh well I thought you meant how you use it
semantically, a static variable is a property that is common to all instances of the class, or a property of the class itself
well in that case no
yeah
but removing the static keyword does not make it work obviously
now apply that logic down a level. imagine that you had finer categories.
maybe, say, class Feline extends Animal, class Cat/Lion/Tiger/Bobcat extends Feline
does every Feline necessarily share the same diet?
that's why i said imagine
I just have plain classes that are subclasses of 1 class
take this logically, not within the bounds of your problem
objects in OOP are meant to represent real things, thinking of the real things can help you with design
what about a broader category? do all fish necessarily have the same diet?
no, right? so down a level, the extensions of Animal, also shouldn't have static diets.
sure
but how is this relevant though
again, OOP models real things, so the real relationships will be represented as well
it'll click once we go along, i hope.
let's go back to Animal.
I understand OOP trust me
each instance of Animal, which would represent a single animal, has a specific diet, right?
this is not an issue of me not understanding concepts of programming as a whole
more me not understanding syntax and behaviour of java itself
...imma be honest, understanding python OOP is kinda not the same as understanding OOP everywhere else
and like I said trust me I know OOP
but well, if you say so
imma just skip ahead, check if there's anything unexpected?
dietis an instance field ofAnimaldesiredHomeTypeis an instance field ofAnimal- both of those are inherited to subclasses
Animalneeds some way to initializediet/desiredHomeType, via its constructor- subclasses of
Animalcan pass the specificdiet/desiredHomeTypeto the superconstructor, while propagating thehomeandnamearguments
Animal needs some way to initialize diet/desiredHomeType, via its constructor
no the opposite it needs to be hard coded in like in my example
no, the class itself.
im just trying to mimic the behaviour of Animal.diet
but then I dont have Animal
but any of my subcalsses of Animal
it is hardcoded. it's hardcoded in the subclasses, not in Animal.
and in the code it doenst need to know which one
yes
the constructor is the public Animal() part right?
which... is the point of doing all this?
yeah
that doenst have anything to do with those variables
im talkinb about Animal not animal
the class itself
becasue I dont have the instance
Animal.diet is a logical error.
I need the class variables to create the instance
you do not.
public boolean addAnimal(
Class<Animal> animalClass,
String name,
HomeType homeType
) {
if (this.nameExists(name)) {
return false;
}
Home home = this.findHome(animalClass, homeType);
if (home == null) {
return false;
}
Animal animal = new Animal(name, home);
home.animals.add(animal);
return true;
}``` how would I do this without having an instance
im not sure what exactly you're trying to do there.
is it trying to instantiate some arbitrary Animal?
yes
that code ive shown before
then you don't need it.
you would make one. without using Animal nor Class
classes in pythons are just functions that return nice objects
how would I do that
you can do that in java too
I think I just dont really know how to anotate Class<Animal>
bc that isnt correct
but I dont know what is
I basically need this I guess
a BiFunction<String, Home, ? extends Animal> could be passed.
the BiFunction is how you say in java, some function that takes 2 arguments and returns a new value
you could pass (name, home) -> new Lion(name, home) as that, which is a lambda function
??? animalClass
if (number == 1) {
animalClass = Lion
} else if (number == 2) {
animalClass = Giraffe
} etc etc```
what would be the ??? in my example
more succinctly, you could do Lion::new, which references the constructor
nothing. classes are not first-class members.
that design does not work in java.
you can use the BiFunction to represent the constructors instead, like i showed above
would that be like a lambda
that's what i just said
idk the exact syntax of lambdas in python mate
....come again?
java*
lamdba x: v?
ok. well i just showed you that.
and a version that acts kinda like the class is a first-class member.
this partly depends on knowledge of java-specific stuff, namely how lambdas work in java.
waht would the ? be here
would a BiFunction be equivallent to Callable in python?
BiFunction<arg1, ..., argn, return>
the ? there is used literally, it's a wildcard.
java's generic system defines that even if T extends U, X<T> does not extend X<U>
wildcards are used to resolve this. ? extends Animal means any type can be used here, as long as it extends Animal.
further reading
no, java's type system is static
there's a different interface for each signature; or if there isn't, make one yourself
why would you need that instaed of just Animal
does that not allow Animal subclasses
that's how java's type system works
it doesn't matter here, but it absolutely does elsewhere
what would be the difference?
List<Object> allows any object to be added
if you construct a List<String>, that should only have strings, but if you then assign that to a variable of type List<Object>, suddenly you can add any object
so java does not define that List<String> extends List<Object>
Are you talking about ArrayList or is that something else
java arrays get this wrong, actually. String[] is a subtype of Object[], and methods/indexing are bivariant, so you could do the issue performed above with no compiler error, however you'd get a runtime exception, ArrayStoreException.
List is an interface that ArrayList implements using an array
LinkedList also implementst that interface, using linked nodes
btw would that just be for method annotations
if I were to have
Animal animal = ...;```
could that also be ```java
? extends Animal animal = ...;```
annotations are a specific thing in java, and this certainly isn't it. im not sure what you mean by "method annotations" here.
no, since ? is a syntax exclusive to generics
since java's type system is static, type hints aren't optional, so they aren't called hints/annotations, fyi
they'd be "declared types" here
and it's exclusive to generics to solve a problem exclusive to generics (not counting arrays)
this doenst seem to be working in interfaces
using types directly doesn't have this issue, since methods get overloaded and not overridden
? is only valid when passed, not when defining generics. there's no point to defining a wildcard generic, since it's just unused
oh right
public ArrayList<? extends Animal> animals = new ArrayList<>();
public ArrayList<Animal> animals = new ArrayList<>();```
the first would be better than the latter correct?
not better, just different
with the latter, any animal will be allowed to be added. you can't guarantee that with the former
but if you need to accept some unknown list, that might all be of the same subclass, and have the list declared as such, then it'd only be assignable to the former
im not sure I understand this
do you have a quick example of what would be allowed in the former and not in the latter
or the other way around
ArrayList<? extends Animal> wildcard = new ArrayList<Lion>();
ArrayList<Animal> exact = new ArrayList<>();
wildcard.add(new Tiger()); // error
exact.add(new Tiger()); // fine
wildcard = new ArrayList<Tiger>(); // fine
exact = new ArrayList<Tiger>(); // error
what would be the difference between if you were to replace ? extends Animal with Lion in the first line
oh wait
other subtypes of animal wouldn't be usable
Is there any difference between
ArrayList<? extends Animal> wildcard = new ArrayList<Lion>();```
and
```java
ArrayList<Animal> wildcard = new ArrayList<Lion>();```
Isnt saying "? extends Animal" equivelant to just "Animal"?
no, and the message you're replying to demonstrates the difference. the latter is invalid.
gotcha
Dev.java: The Destination for Java Developers
Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs.