|
Public class Main { // Statik (static) metod static void
|
bet | 5/6 | Sana | 17.12.2023 | Hajmi | 21,46 Kb. | | #121647 |
Bog'liq Java Class Methods1public class Main {
// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}
// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
public static void main(String[] args) {
myStaticMethod(); // Statik metodni chaqirish
// myPublicMethod(); Bu xato chiqaradi
Main myObj = new Main(); // Main klassining obyektini yaratish
myObj.myPublicMethod(); // Ob'yekt bo'yicha public metodni chaqirish
}
}
Bu misolda, myStaticMethod statik metodni chaqirish uchun obyekt yaratish talab qilmaydi, lekin myPublicMethod public metodni chaqirish uchun obyekt yaratish kerak.
`abstract`
`abstract` modifikatori bir abstract klassning bir abstract metodiga ega bo'lishini anglatadi. Bu abstract metodni o'z ichiga oladi, ya'ni uning ichida ishlatiladigan kod yo'q. U metodning asosi bu metodni meros qilgan subclass tomonidan beriladi.
Main.java fayli:
// abstract class
abstract class Main {
public String fname = "John";
public int age = 21;
public abstract void study(); // abstract method
}
// Subclass (inherit from Main)
class Student extends Main {
public int graduationYear = 2018;
public void study() { // the body of the abstract method is provided here
System.out.println("Studying all day long");
}
}
Test.java fayli
class Second {
public static void main(String[] args) {
// create an object of the Student class (which inherits attributes and methods from Main)
Student myObj =
|
| |