Java - Class and Object confusion

class Dog {   // this is Class
  int age;

	public Dog(int dogsAge) {  // what we call this line?
    dogsAge = age;               // why are we defining dogsAge = age; ?

public void bark(){                              // what we call this line?

  public void run(int feet){
    System.out.println("your dog ran " + feet +" feet!");
	public static void main(String[] args) {
    Dog spike = new Dog(5);

sorry if this sounds stupid. I never got about class, object. if someone can explain, It would really be grateful.

its the constructor, its a method but its automatically called when you create an instance of your class.


Dog spike = new Dog(5);

you create an instance named spike, which will cause the constructor to execute.

age is instance variable, it has a different value for each instance, so when we create a new Dog(argument); we pass an argument (5 for spike) to the constructor, so we can set the instance variable.

a public method which doens’t return anything (void) named bark

One thing I don’t understand about this is why do you create an instance of a Dog (spike) within the Dog class? I thought the class was the template.

(Or maybe its just how I’m interpreting this code)

Ideally we should have a Main and Dog class.

Java main method is the entry point of any java program. Its syntax is always public static void main(String[] args)

even though its in a class, main method is special

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.