Course Content
Java Extended
Java Extended
What is class?
Class
A class is a fundamental concept in OOP programming. It refers to a template for creating objects. A class consists of fields (data) and methods (behavior). Let's consider the class Dog
, where the fields (data) would be information about the dog's name
and age
, and the method (behavior) would make the dog introduce itself and say its name:
Dog
class Dog { String name; int age; void introduce() { System.out.println("Woof, woof (which means 'My name is " + name + "!')."); } }
Let's consider what constitutes data (fields) and what represents behavior (methods):
As we can see from the diagram, we have fields that are not initialized within the class itself, as well as a method that is not yet called anywhere. Let's create an object of the Dog
class in the main class and initialize its fields:
Main
public class Main { public static void main(String[] args) { Dog dog = new Dog(); dog.name = "Brian"; dog.age = 13; } }
We created an object of the Dog
class and named it dog
.
The syntax for creating an object of a class is:
ClassName objectName = new ClassName();
We also initialized the properties of the object by assigning values to the fields.
Our dog's name is Brian
, and the age is 13
.
The syntax for initializing the fields of an object is:
objectName.fieldName = value;
So now we have an object of the Dog
class with initialized fields.
Let's now invoke a method from our Dog
class:
Main
package com.example; class Dog { String name; int age; void introduce() { System.out.println("Woof, woof (which means 'My name is " + name + "!')."); } } public class Main { public static void main(String[] args) { Dog dog = new Dog(); dog.name = "Brian"; dog.age = 13; dog.introduce(); } }
We successfully invoked a method from the Dog
class by using that method on the Dog
object. You may have noticed the same syntax when we called methods from the String
class earlier.
Thanks for your feedback!