object oriented programing ' code example
Example 1: object oriented programming
// OOP is a programming paradigm found in many languages today.
// Generally, an object is an instance of a Class.
// Here's a Java example:
public class Car
{
private double speed;
public Car(double initialSpeed) // Constructor, most common way to initialize objects of a class.
{
speed = initialSpeed;
}
// Accessor methods, aka getters
public double getSpeed()
{
return speed;
// This is an example of encapsulation, where
// methods are used to hide the implementation details
// and ensure the programmer can't modify things they shouldn't be able to.
}
public void accelerate()
{
speed++;
}
public void slowDown()
{
speed--;
}
}
Example 2: object-oriented programming
class Person {
void walk() {
System.out.println(“Can Run….”);
}
}
class Employee extends Person {
void walk() {
System.out.println(“Running Fast…”);
}
public static void main(String arg[]) {
Person p = new Employee(); //upcasting
p.walk();
}
}