Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Luokkametodit | Johdatus Olio-Ohjelmointiin (OOP)
C# Perusteiden Jälkeen

bookLuokkametodit

Kuten rakenteilla, myös luokilla voi olla metodeja. Metodien luomisen ja kutsumisen syntaksi on myös hyvin samanlainen.

Voit esimerkiksi luoda luokan nimeltä Rectangle, jolla on width- ja height-attribuutit sekä metodi nimeltä area, joka laskee suorakulmion pinta-alan width- ja height-arvojen perusteella:

index.cs

index.cs

copy
1234567
class className { // ... other class code public returnType methodName(datatype param1, datatype param2, ...) { // code } }
index.cs

index.cs

copy
123456789101112131415161718192021222324252627
using System; public class ConsoleApp { class Rectangle { public double width; public double height; public double area() { return width * height; } } public static void Main(string[] args) { Rectangle r1 = new Rectangle(); r1.width = 10; r1.height = 20; Rectangle r2 = new Rectangle(); r2.width = 14.7; r2.height= 17.9; Console.WriteLine($"Area of R1 is {r1.area()}"); Console.WriteLine($"Area of R2 is {r2.area()}"); } }
question mark

Mikä seuraavista on kelvollinen metodi?

Select the correct answer

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 3. Luku 7

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Suggested prompts:

Can you show me how to define a method inside a class?

How do I call a method from an instance of a class?

What is the difference between a method and a regular function in a class?

Awesome!

Completion rate improved to 2.04

bookLuokkametodit

Pyyhkäise näyttääksesi valikon

Kuten rakenteilla, myös luokilla voi olla metodeja. Metodien luomisen ja kutsumisen syntaksi on myös hyvin samanlainen.

Voit esimerkiksi luoda luokan nimeltä Rectangle, jolla on width- ja height-attribuutit sekä metodi nimeltä area, joka laskee suorakulmion pinta-alan width- ja height-arvojen perusteella:

index.cs

index.cs

copy
1234567
class className { // ... other class code public returnType methodName(datatype param1, datatype param2, ...) { // code } }
index.cs

index.cs

copy
123456789101112131415161718192021222324252627
using System; public class ConsoleApp { class Rectangle { public double width; public double height; public double area() { return width * height; } } public static void Main(string[] args) { Rectangle r1 = new Rectangle(); r1.width = 10; r1.height = 20; Rectangle r2 = new Rectangle(); r2.width = 14.7; r2.height= 17.9; Console.WriteLine($"Area of R1 is {r1.area()}"); Console.WriteLine($"Area of R2 is {r2.area()}"); } }
question mark

Mikä seuraavista on kelvollinen metodi?

Select the correct answer

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 3. Luku 7
some-alt