0

newb here, I've got following code and was wondering how to grasp the class-concept.

I realize I cannot call a non-static method from main. So what exactly is it I am doing here instead? calling the isSameName-method through an object of the non-static Person-class, through the main-method? I also don't understand the relationship between the class-objects, as my object kira is not relevant, but can still use it to call the method with my relevant parameters

class Person {
    private String name;
    private int alter;

    public Person(String name, int alter) {
        this.name = name;
        this.alter = alter;
    }

    public String getName() {
        return name;
    }

    public int getAlter() {
        return alter;
    }

    public boolean isSameName(Person a, Person b) {
        return a.getName() == b.getName();
    }


    public static void main(String[] args) {
        Person tom = new Person("Tom", 23);
        Person kira = new Person("Kira", 34);
        Person tim = new Person("Tom", 45);
        
        System.out.println(kira.isSameName(tom, tim));
    }
}

would be grateful for any help, and sorry if questions like this were asked a thousand times, I still have problems finding the right words for my search, as I don't know how to even call my problems

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Reyth
  • 1
  • 1
  • 1
    "as my object kirais not relevant" <- Thats because you programmed the isSameName method to not use anything from the object it belongs to. You would usually either only pass one Person as an argument and then compare `a.getName()` (The passed argument name) to `this.getName()` (The name of object you are calling the method on) for example or you would make that method static. So yes, your object is not relevant, but that is because of your bad design and nothing else. – OH GOD SPIDERS Apr 16 '21 at 12:01
  • 1
    [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Lino Apr 16 '21 at 12:03
  • Also, you should not compare equality of strings using `==`. Use `equals` instead – Felix Apr 16 '21 at 12:05
  • Either isSameName() should take a single name and compare it to the object's name, or it should be static. – NomadMaker Apr 16 '21 at 12:59

0 Answers0