نموذج C
نموذج C
Java achieves object-oriented programming (OOP) through its fundamental concepts of classes
and objects, which allow developers to model real-world entities and behaviors by:
Classes
Objects
Encapsulation
Inheritance
Polymorphism
Example:
// Class definition
class Car {
String model;
// Constructor
Car(String model) {
this.model = model;
}
// Method
void display() {
System.out.println("Car model: " + model);
}
}
2) What does the purpose of the ternary operator in Java? provide an example.
The ternary operator (?:) is a shorthand operator for an if-else statement. It makes your code
compact and more readable.
Example:
int age = 18;
String access = (age >= 18) ? "Access granted" : "Access denied";
System.out.println(access);
3) What's the difference between if and switch statements?
Java handles object-oriented principles like polymorphism primarily through method overloading
and method overriding.
Example:
class MathOperations {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
The private specifier restricts access to members only within the same class.
The protected specifier allows access to members within the same package and also in subclasses
(even in different packages)
Platform independence in Java means that Java programs can run on any operating system
without modification. This is achieved through the use of bytecode, which is compiled from Java
source code. When the code is executed, the Java Virtual Machine (JVM) on any platform
interprets the bytecode and translates it into machine-specific instructions.
Example:
can be compiled into HelloWorld.class bytecode. This bytecode can run on any system with a
JVM (like Windows, Linux, or macOS) using the command java HelloWorld, producing the
same output on all platforms.
7) Explain the purpose of the import statement in Java and provide an example.
help to narrow down the search performed by the Java compiler by informing it about the classes
and packages used in the class.
Example:
import java.util.Scanner;
input.close();
}
}