#Some basic java help

337 messages · Page 1 of 1 (latest)

echo token
#
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
noble perchBOT
#

This post has been reserved for your question.

Hey @echo token! Please use /close or the Close Post button 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.

echo token
#

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

merry edge
#

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

echo token
#

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

merry edge
#

well.. you can just access those static variables from said class directly

#

so you want to inherit from Foo?

echo token
#

Foo inside of Class<Foo> would be a subclass of Foo

merry edge
#

it wouldn't

echo token
#

Are there any alternatives for what I’m trying to do

merry edge
#

/run

class X { public static void main(String[] args) {
Class<Object> cls = String.class;
}}
snow ingotBOT
#

@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
merry edge
echo token
merry edge
#

honestly, it sounds like xyproblem

merry edge
echo token
#

Like I said kind of hard to explain

#

I can share working python code aswell of the thing I’m trying to do

merry edge
#

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

echo token
#

Not at my pc atm tho, give me 15 minutes

merry edge
#

(please strip it down to just the relevant part though)

echo token
#
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

merry edge
#

why do Subn have to be classes there to begin with?

echo token
#

this would print 1 2 3 as expected

echo token
merry edge
#

why can't you just

class X:
  def __init__(self, x: int):
    self.x = x;

sub1 = X(1)
# ...
merry edge
#

what you use something for kinda heavily influences the design.

echo token
#

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

merry edge
#

python doesn't have a way to denote things that don't change

echo token
#

thats why I type hinted it as a class var

#

well not during runtime but typing.ClassVar is for that

merry edge
#

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?

echo token
#

honestly i cant explain it better than how I have

merry edge
echo token
merry edge
#

you stripped too much out of your description, you left out the motivation behind your python implementation

#

again; why can't they be instances?

echo token
#

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

merry edge
#

no, the instance itself defines x.

echo token
#

then I dont understand what youre asking

#

in my example

merry edge
#

instead of having Subn extend Super, they can be instances of Super

echo token
#

I need to use desiredHomeType to check if there is a valid Home

echo token
#

in that example they can but thats not my point

echo token
merry edge
echo token
#

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

merry edge
echo token
#

I dont really see how

echo token
merry edge
merry edge
#

"minimal" is not least code, minimal is least code to explain your issue

echo token
#

honestly if you have a better way to do it wiht my actual use case (the java code I just sent) im all ears

merry edge
#

if you strip out a part that causes problems, how are we supposed to identify the problems we can't see?

echo token
#

the python code worked fine

#

perfectly as expected

#

I wanna (sort of) replicate that in java

merry edge
echo token
#

trust me I really dont

#

Im employed in python have been doing it for years

merry edge
#
Animal lion = new Animal(DietType.Carnivore); // lion will always have the same diet
merry edge
echo token
#

I dont want the user to have to specify that a lion will have a carnivore diet

merry edge
#

and the user doesn't have to do that.

echo token
#

beacuse frankly a Lion in my code will always have that

merry edge
#

just like the user doesn't have to define the class Lion. you can do that for them.

merry edge
echo token
merry edge
#

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.

echo token
#

youve told me but not shown me

merry edge
#

i literally did show you

echo token
#

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

merry edge
#

and that's why i asked if it was for defining an interface.

#

dude you aren't listening to me

echo token
#

I am

#

is this defining an interface? I thought interface you meant an actual interface

#
interface Foo {}```
merry edge
echo token
#

but I thought in Java interfaces were solely for methods

#

which mine is not

#

mine would be solely for variables

echo token
#

and it would need a constructor aswell

echo token
merry edge
#

...no, you're construing ideas

echo token
#

they are hard coded variables which will never change

merry edge
#

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;

echo token
#

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

merry edge
echo token
#

based on that, I create an Animal class

merry edge
#

uhhhhh no?

echo token
#

possible as in not allowed by the homework assignment

merry edge
#

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

echo token
#

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.

merry edge
#

ok, that part is not possible. at least not cleanly.

echo token
#

then I call addAnimal with this class and a home

#

home I also get with a number from input

merry edge
#

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?

echo token
#

yes

#

what I was trying to do, in python terms because am way more familiar with said syntax:

merry edge
#

i have an implementation idea in mind, but give me a sec to see what other stuff is possible.

echo token
#


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

noble perchBOT
# echo token 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.

echo token
#

lol does it have some filter that checks for the word thanks

#

thanks

#

also I timer I suppose

merry edge
#

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?

echo token
#

yes

#

every species of animal eats the same diet

#

all these variables will never cahnge

merry edge
#

ok i phrased that horribly sec

echo token
#

should I make those final aswell or is that bad?

merry edge
#
Animal a; Diet d;
a = getRandomAnimal();
d = a.diet;
a = getRandomAnimal();
d == a.diet ?
#

should any 2 arbitrary animals always have the same diet

echo token
#

no not if theyre different species

#

I left out a lot of animals

merry edge
#

so should Animal.diet be static?

echo token
#

yes

#

should never cahnge

merry edge
#

but it does change, across species. you just said so.

echo token
#

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

merry edge
#

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?

echo token
#

like I said animals from different species can have different diets

#

animals from the same species have the same diet

#

it does not change

merry edge
#

a static Animal.diet means that every single animal shares the same diet

#

so that's a contradiction

echo token
#

youre looking at my code

merry edge
echo token
#

look what im saying

merry edge
#

im looking at both your code and your words

echo token
#

im not very familiar with java, tahts why im asking for help

merry edge
#

im not really talking about java right now

#

this is just a logical contradiction

echo token
#

for the third time:
every animal has the SAME DIET as animals that have the SAME SPECIES

merry edge
#

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

echo token
#

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

merry edge
#

of the same species.

#

Animal, is not for the same species

#

diet and desiredHomeType should not be static.

#

there, i said it.

echo token
#

no I guess my Animal class is acting as an interface

#

but with variables

merry edge
#

which doesn't work.

echo token
#

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

merry edge
#

that's the syntactic (how you use it) meaning, not the semantic (what it means) meaning

echo token
#

oh well I thought you meant how you use it

merry edge
#

semantically, a static variable is a property that is common to all instances of the class, or a property of the class itself

echo token
#

well in that case no

merry edge
#

yeah

echo token
#

but removing the static keyword does not make it work obviously

merry edge
#

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?

echo token
#

I mean

#

I dont know

#

that would go beyond what im trying to do

merry edge
#

that's why i said imagine

echo token
#

I just have plain classes that are subclasses of 1 class

merry edge
#

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.

echo token
#

sure

merry edge
echo token
#

but how is this relevant though

merry edge
#

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.

echo token
#

I understand OOP trust me

merry edge
#

each instance of Animal, which would represent a single animal, has a specific diet, right?

echo token
#

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

merry edge
echo token
#

and like I said trust me I know OOP

merry edge
#

but well, if you say so

echo token
#

more than just python

#

ive just done the most python in total thats all

merry edge
#

imma just skip ahead, check if there's anything unexpected?

  • diet is an instance field of Animal
  • desiredHomeType is an instance field of Animal
  • both of those are inherited to subclasses
  • Animal needs some way to initialize diet/desiredHomeType, via its constructor
  • subclasses of Animal can pass the specific diet/desiredHomeType to the superconstructor, while propagating the home and name arguments
echo token
#

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

echo token
#

im just trying to mimic the behaviour of Animal.diet

#

but then I dont have Animal

#

but any of my subcalsses of Animal

merry edge
#

it is hardcoded. it's hardcoded in the subclasses, not in Animal.

echo token
#

and in the code it doenst need to know which one

echo token
#

the constructor is the public Animal() part right?

merry edge
#

yeah

echo token
#

that doenst have anything to do with those variables

merry edge
#

animal.diet is available now.

#

for all animals.

echo token
#

im talkinb about Animal not animal

#

the class itself

#

becasue I dont have the instance

merry edge
#

Animal.diet is a logical error.

echo token
#

I need the class variables to create the instance

merry edge
#

you do not.

echo token
#
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
merry edge
#

im not sure what exactly you're trying to do there.

echo token
#

then dont tell me I dont need it

#

because I do

merry edge
#

is it trying to instantiate some arbitrary Animal?

echo token
#

that code ive shown before

merry edge
#

then you don't need it.

merry edge
#

classes in pythons are just functions that return nice objects

echo token
#

how would I do that

merry edge
#

you can do that in java too

echo token
#

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

merry edge
#

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

echo token
#
??? animalClass
if (number == 1) {
  animalClass = Lion
} else if (number == 2) {
  animalClass = Giraffe
} etc etc```
#

what would be the ??? in my example

merry edge
merry edge
#

that design does not work in java.

#

you can use the BiFunction to represent the constructors instead, like i showed above

echo token
#

would that be like a lambda

merry edge
#

that's what i just said

echo token
#

idk the exact syntax of lambdas in python mate

merry edge
#

....come again?

echo token
#

java*

merry edge
#

lamdba x: v?

merry edge
merry edge
echo token
#

would a BiFunction be equivallent to Callable in python?

#

BiFunction<arg1, ..., argn, return>

merry edge
# echo token waht would the ? be here

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

echo token
#

oh nvm its actual binary function

#

2 args max

#

and min

merry edge
#

there's a different interface for each signature; or if there isn't, make one yourself

echo token
#

does that not allow Animal subclasses

merry edge
#

that's how java's type system works

#

it doesn't matter here, but it absolutely does elsewhere

echo token
#

what would be the difference?

merry edge
#

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>

echo token
#

Are you talking about ArrayList or is that something else

merry edge
#

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.

merry edge
echo token
#

if I were to have

#
Animal animal = ...;```
could that also be ```java
? extends Animal animal = ...;```
merry edge
#

annotations are a specific thing in java, and this certainly isn't it. im not sure what you mean by "method annotations" here.

echo token
#

I mean like the type part

#

the Animal in Animal animal = someAnimal

merry edge
merry edge
merry edge
echo token
merry edge
#

using types directly doesn't have this issue, since methods get overloaded and not overridden

merry edge
echo token
#

oh right

#
public ArrayList<? extends Animal> animals = new ArrayList<>();
public ArrayList<Animal> animals = new ArrayList<>();```
the first would be better than the latter correct?
merry edge
#

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

echo token
#

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

merry edge
#
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
echo token
#

what would be the difference between if you were to replace ? extends Animal with Lion in the first line

#

oh wait

merry edge
#

other subtypes of animal wouldn't be usable

red shell
merry edge
red shell
#

gotcha

merry edge
# red shell gotcha
red shell
#

oh weird ive never had to do that

#

but I see where its different ty