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

Зміст курсу

Java Extended

Java Extended

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

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:

java

Dog

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

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

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. Yes, String is also written by someone. It has fields and methods that we use effectively. Now it's your turn to write your own classes!

Note

A new class should always be located outside the body of another class or method. In other words, the class itself is the container for other fields and methods. Remember this to avoid syntax errors.

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

How to declare a class?

Виберіть правильну відповідь

Should we create a new class inside another class?

Виберіть правильну відповідь

Все було зрозуміло?

Секція 4. Розділ 1
We're sorry to hear that something went wrong. What happened?
some-alt