Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
What is Class? | Classes
Java Extended
course content

Course Content

Java Extended

Java Extended

1. Deep Java Structure
2. Methods
3. String Advanced
4. Classes
5. Classes Advanced

bookWhat 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:

java

Dog

copy
12345678
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:

java

Main

copy
1234567
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:

java

Main

copy
1234567891011121314151617181920
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.

1. How to declare a class?
2. Should we create a new class inside another class?
How to declare a class?

How to declare a class?

Select the correct answer

Should we create a new class inside another class?

Should we create a new class inside another class?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 1
We're sorry to hear that something went wrong. What happened?
some-alt