DEV Community

Vaniusca 23
Vaniusca 23

Posted on

Java methods and classes examples

  1. What is a Class in Java? A class is a blueprint for creating objects. It defines attributes (variables) and methods (functions) that describe the behavior of an object.

Basic Syntax of a Class

`// defining a class
public class Car {
// attributes (variables)
String brand;
int speed;

// method (function)
void honk() {
    System.out.println("Beep Beep!");
}
Enter fullscreen mode Exit fullscreen mode

}`
📌 Explanation:

Car is a class.
brand and speed are attributes (also called instance variables).
honk() is a method (a function inside a class).

  1. How to Create an Object? An object is an instance of a class. You create objects using the new keyword.

Creating an Object in Java

`public class Main {
public static void main(String[] args) {
// creating an object of the Car class
Car myCar = new Car();

    // assigning values to attributes
    myCar.brand = "Toyota";
    myCar.speed = 120;

    // calling a method
    myCar.honk();

    // printing attributes
    System.out.println("Brand: " + myCar.brand);
    System.out.println("Speed: " + myCar.speed + " km/h");
}
Enter fullscreen mode Exit fullscreen mode

}`
🔹 Output:

makefile
Beep Beep!
Brand: Toyota
Speed: 120 km/h
📌 Explanation:

Car myCar = new Car(); → Creates an object named myCar.
myCar.brand = "Toyota"; → Assigns a value to brand.
myCar.honk(); → Calls the honk() method.

  1. Constructors in Java A constructor is a special method that is automatically called when an object is created.

Example of a Constructor

`public class Car {
String brand;
int speed;

// constructor
public Car(String brand, int speed) {
    this.brand = brand;
    this.speed = speed;
}

// method to display car details
void displayCar() {
    System.out.println("Brand: " + brand);
    System.out.println("Speed: " + speed + " km/h");
}
Enter fullscreen mode Exit fullscreen mode

}

public class Main {
public static void main(String[] args) {
// using constructor to initialize values
Car myCar = new Car("Honda", 150);
myCar.displayCar();
}
}`
🔹 Output:

Brand: Honda
Speed: 150 km/h
📌 Explanation:

The constructor Car(String brand, int speed) initializes attributes when the object is created.
The this keyword refers to the current object's instance.

  1. Types of Methods in Java Java has two types of methods:

Instance Methods (work with object data)
Static Methods (belong to the class, not objects)
Example of Instance and Static Methods

`public class MathOperations {
// instance method
int square(int x) {
return x * x;
}

// static method
static int add(int a, int b) {
    return a + b;
}
Enter fullscreen mode Exit fullscreen mode

}

public class Main {
public static void main(String[] args) {
// calling an instance method
MathOperations math = new MathOperations();
int result = math.square(5);
System.out.println("Square: " + result);

    // calling a static method
    int sum = MathOperations.add(10, 20);
    System.out.println("Sum: " + sum);
}
Enter fullscreen mode Exit fullscreen mode

}`
🔹 Output:

Square: 25
Sum: 30
📌 Explanation:

square(int x) is an instance method, so we need to create an object (math.square(5);).
add(int a, int b) is a static method, so we can call it directly using the class name (MathOperations.add(10, 20);).

  1. Method Overloading in Java Method Overloading allows multiple methods with the same name but different parameters.

Example of Method Overloading

`public class Calculator {
// method with two parameters
int add(int a, int b) {
return a + b;
}

// overloaded method with three parameters
int add(int a, int b, int c) {
    return a + b + c;
}
Enter fullscreen mode Exit fullscreen mode

}

public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("Sum (2 numbers): " + calc.add(10, 20));
System.out.println("Sum (3 numbers): " + calc.add(10, 20, 30));
}
}`
🔹 Output:

Sum (2 numbers): 30
Sum (3 numbers): 60
📌 Explanation:

The method add() is overloaded (two versions with different numbers of parameters).
The compiler automatically selects the correct method.

// clasa student
public class Student {
private String stdNume, denDisc1, denDisc2, denDisc3; // nume student si discipline
private int note1, note2, note3; // note pentru discipline

// constructor
public Student(String stdNume, String denDisc1, String denDisc2, String denDisc3) {
this.stdNume = stdNume;
this.denDisc1 = denDisc1;
this.denDisc2 = denDisc2;
this.denDisc3 = denDisc3;
this.note1 = 0;
this.note2 = 0;
this.note3 = 0;
}

// get/set nume
public String getNume() { return stdNume; }
public void setNume(String stdNume) { this.stdNume = stdNume; }

// get/set disciplina 1
public String getDisc1() { return denDisc1; }
public void setDisc1(String denDisc1) { this.denDisc1 = denDisc1; }

// get/set disciplina 2
public String getDisc2() { return denDisc2; }
public void setDisc2(String denDisc2) { this.denDisc2 = denDisc2; }

// get/set disciplina 3
public String getDisc3() { return denDisc3; }
public void setDisc3(String denDisc3) { this.denDisc3 = denDisc3; }

// get/set nota 1
public int getNota1() { return note1; }
public void setNota1(int note1) { this.note1 = note1; }

// get/set nota 2
public int getNota2() { return note2; }
public void setNota2(int note2) { this.note2 = note2; }

// get/set nota 3
public int getNota3() { return note3; }
public void setNota3(int note3) { this.note3 = note3; }

// toString
@override
public String toString() {
return "student: " + stdNume + "\n" +
"disciplina 1: " + denDisc1 + " nota: " + note1 + "\n" +
"disciplina 2: " + denDisc2 + " nota: " + note2 + "\n" +
"disciplina 3: " + denDisc3 + " nota: " + note3;
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
import java.awt.*;

// clasa principala
public class TihanIoan extends Frame {
private Choice cmbDiscipline; // combobox
private List listaNote; // lista note
private TextField txtNota; // caseta text
private Label lblInfo; // eticheta
private Button btnSetNota, btnAdauga, btnAfisare; // butoane
private Student student; // obiect student

public TihanIoan() {
// initializare student
student = new Student("Ioan Tihan", "Matematica", "Informatica", "Fizica");

   // setari fereastra
   setTitle("formular student");
   setSize(400, 300);
   setLayout(new FlowLayout());


   // combobox discipline
   cmbDiscipline = new Choice();
   cmbDiscipline.add(student.getDisc1());
   cmbDiscipline.add(student.getDisc2());
   cmbDiscipline.add(student.getDisc3());
   add(cmbDiscipline);


   // caseta text pentru nota
   txtNota = new TextField(10);
   add(new Label("Introdu nota:"));
   add(txtNota);


   // lista note
   listaNote = new List();
   add(listaNote);


   // butoane
   btnSetNota = new Button("Set Nota");
   btnAdauga = new Button("Adauga Nota");
   btnAfisare = new Button("Afiseaza Info");


   add(btnSetNota);
   add(btnAdauga);
   add(btnAfisare);


   // eticheta informatii
   lblInfo = new Label("detalii student");
   add(lblInfo);


   // inchidere fereastra
   addWindowListener(new java.awt.event.WindowAdapter() {
       public void windowClosing(java.awt.event.WindowEvent e) {
           dispose();
       }
   });


   setVisible(true);
Enter fullscreen mode Exit fullscreen mode

}

public static void main(String[] args) {
new TihanIoan();
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
import java.awt.;
import java.awt.event.
;
import java.util.ArrayList;

public class TihanIoan extends Frame {
private Choice discipline;
private List noteList;
private TextField notaField;
private TextArea infoArea;
private Student student;
private ArrayList noteDisc1, noteDisc2, noteDisc3;

public TihanIoan() {
student = new Student("Ioan Tihan", "Matematica", "Informatica", "Fizica");
noteDisc1 = new ArrayList<>();
noteDisc2 = new ArrayList<>();
noteDisc3 = new ArrayList<>();

   setLayout(new FlowLayout());
   setSize(500, 350);




   discipline = new Choice();
   discipline.add(student.getDisc1());
   discipline.add(student.getDisc2());
   discipline.add(student.getDisc3());
   add(discipline);




   noteList = new List();
   add(noteList);




   notaField = new TextField(5);
   add(notaField);




   Button afisareNote = new Button("Afisare Note");
   afisareNote.addActionListener(e -> afiseazaNote());
   add(afisareNote);




   Button adaugaNota = new Button("Adauga Nota");
   adaugaNota.addActionListener(e -> adaugaNota());
   add(adaugaNota);




   Button afisareInfo = new Button("Afisare Info");
   afisareInfo.addActionListener(e -> afiseazaInfo());
   add(afisareInfo);




   infoArea = new TextArea(7, 50);
   infoArea.setEditable(false);
   add(infoArea);




   addWindowListener(new WindowAdapter() {
       public void windowClosing(WindowEvent e) {
           dispose();
       }
   });
Enter fullscreen mode Exit fullscreen mode

}

private void afiseazaNote() {
noteList.removeAll();
ArrayList note = getNoteList();
for (int nota : note) {
noteList.add(String.valueOf(nota));
}
}

private void adaugaNota() {
try {
int nota = Integer.parseInt(notaField.getText());
if (nota < 1 || nota > 10) {
infoArea.setText("Introduceți o notă între 1 și 10.");
return;
}

       ArrayList<Integer> note = getNoteList();
       if (!note.isEmpty() && note.get(note.size() - 1) >= 5) {
           infoArea.setText("Studentul a promovat disciplina și nu mai poate adăuga note.");
           return;
       }




       note.add(nota);
       afiseazaNote();
       afiseazaInfo();
   } catch (NumberFormatException e) {
       infoArea.setText("Introduceți o notă validă.");
   }
Enter fullscreen mode Exit fullscreen mode

}

private void afiseazaInfo() {
StringBuilder info = new StringBuilder("Student: " + student.getNume() + "\nNote:\n");
info.append(student.getDisc1()).append(" ").append(noteDisc1).append("\n");
info.append(student.getDisc2()).append(" ").append(noteDisc2).append("\n");
info.append(student.getDisc3()).append(" ").append(noteDisc3);
infoArea.setText(info.toString());
}

private ArrayList getNoteList() {
String disciplina = discipline.getSelectedItem();
if (disciplina.equals(student.getDisc1())) return noteDisc1;
if (disciplina.equals(student.getDisc2())) return noteDisc2;
return noteDisc3;
}

public static void main(String[] args) {
new TihanIoan().setVisible(true);
}
}

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay