BaşlayınÜcretsiz Başlayın

Public class fields

So far, during this course, you have created properties and methods without specifying access modifiers. You will explicitly specify the public access modifier for the appropriate properties within your code.

NOTE: In Java, properties without explicit access modifiers are package-private by default, allowing access similar to public. Also, only one class per file can be explicitly marked as public.

Bu egzersiz

Introduction to Object-Oriented Programming in Java

kursunun bir parçasıdır
Kursu Görüntüle

Egzersiz talimatları

  • Mark the model, and year properties of the Car class public by adding the public access modifiers to them.
  • Turn both the turnEngineOn and calculateMPG methods public by adding the public access modifiers to them.

Uygulamalı interaktif egzersiz

Bu örnek kodu tamamlayarak bu egzersizi bitirin.

public class Main {  

    static class Car {
        public String color;
        // Make "model" and "year" public
        ____ String model;
        ____ int year;

        Car(String color, String model, int year) {
            this.color = color;
            this.model = model;
            this.year = year;
        }

        // Make "turnEngineOn" method public
        ____ void turnEngineOn() {
            System.out.println("engine is on");            
        }

        // Make "calculateMPG" method public
        ____ int calculateMPG(int milesDriven, int gallonsUsed) {
            return milesDriven / gallonsUsed;
        }
    }

    public static void main(String[] args) {
        Car myCar = new Car("red", "camry", 2022);
        System.out.println(myCar.calculateMPG(180, 20));
    }
}
Kodu Düzenle ve Çalıştır