Search code examples
javaclassconceptual

Understanding classes in java


So I'm a little confused about the concept of

Instance methods of a class being called without first instantiating an object

How does that work in java? Would I have to instantiate an object so I can invoke a method on the object.

For example, here are my classes below.

public class Date{
        public String month;
        public int day;
        public int year;
    public void writeOutput()
    {
        System.out.println("Today is : " + this.month + " " + this.day + " , " + this.year);
    }
}

public class DateTest{
    public static void main(String[] yolo){
        Date today;
        today = new Date();
        today.month = "January";
        today.day = 31;
        today.year = 2015;
        today.writeOutput();
    }
}

Hence I would have to instantiate some date first? Can I call an instance method without instantiating a "date" object of some kind?


Solution

  • This is a copy of my comment:

    Can you make a dog bark if it doesn't exists? (and only the concept of the dogs exists). Now imagine the concept of the dog as the class, bark as a method and Rex as an instance of a dog. So yes, you need to instanciate a class (Dog Rex = new Dog();) In order to use a method (Rex.bark()). Of course you can use static methods that allow you to do something like Dog.bark() but that it's not really OOP.