0% found this document useful (0 votes)
3 views12 pages

Java Assignment

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, including advantages of OOP over procedural programming, such as modularity, code reusability, and data security. It includes examples of abstract classes, interfaces, encapsulation, constructors, method overloading and overriding, event-driven programming, and the use of packages. Additionally, it demonstrates practical implementations of these concepts through Java code snippets.

Uploaded by

isaacbaha584
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views12 pages

Java Assignment

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, including advantages of OOP over procedural programming, such as modularity, code reusability, and data security. It includes examples of abstract classes, interfaces, encapsulation, constructors, method overloading and overriding, event-driven programming, and the use of packages. Additionally, it demonstrates practical implementations of these concepts through Java code snippets.

Uploaded by

isaacbaha584
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Name:Isaac Bahati.

Reg No:IN16/00110/24.

Unit code:Soen 240.

Unit Name:Object Oriented Programming In Java (I).

Dept:School Of Information Science and Technology.

Lecturer:Dr Maina.
a).Object oriented programming is a programming model which organizes software design
around objects rather than functions and [Link] object is a self-contained entity that
combines data and behaviour that operate on that data.
Advantages over procedural programming.
(i). Modularity and maintainability: Code is organized into discrete, self contained objects as
opposed to procedural approach where functions and data are seperate leading to scattered
logic.
It is advantageous in that changes made to one object won’t ripple through the entire system.
(ii). Code reusability and reduced redundancy: In the object oriented approach inheritance
reduces code duplication thus code is easily reused as compared to the procedural approach
where duplication of similar logic is done throughout the code. This is advantageous in that
ineritance eliminates code duplication, since common functionality is written once in a parent
class,used by multiple child classes.
(iii). Data security and reduced complexity: Encapsulation protects data integrity through
encapsulation as opposed to the procedural approach where data is exposed and vulnerable.
It is advantageous in that encapsulation prevents invalid state and data validation happens in
one place ensuring consistency.
(iv). Real-world modelling: OOP naturally maps to real-world concepts unlike procedural
approach where artificial seperation of related concepts is [Link] is advantageous in that it
improves program readability and understanding

b). import [Link];

public class PrimeCheck {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

[Link]("Enter an integer: ");


int number = [Link]();

boolean isPrime = true;

if (number <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
}

if (isPrime) {
[Link](number + " is a prime number.");
} else {
[Link](number + " is not a prime number.");
}

[Link]();
}
}

c).

An abstract class is a class that can’t be instantiated on its own and can contain both abstract
methods and concrete methods.
Example.

Suppose you are modeling different types of vehicles. All vehicles have a start() behavior, but
each type of vehicle might have a different fuelEfficiency() calculation.

abstract class Vehicle {


String brand;

Vehicle(String brand) {
[Link] = brand;
}

// Concrete method
void start() {
[Link](brand + " vehicle is starting.");
}

// Abstract method
abstract double fuelEfficiency();
}

class Car extends Vehicle {


double mpg;

Car(String brand, double mpg) {


super(brand);
[Link] = mpg;
}

@Override
double fuelEfficiency() {
return mpg;
}
}
Here vehicle is an abstract because it provides common behaviour but leaves some methods
abstract for subclasses to implement.

Interfaces.

An interface is a contract that defines a set of abstract [Link] implement interfaces to


provide concrete behaviour.
Interfaces involve all methods being implicitly abstract , no instance variables and it also
supports multiple inheritance.

Example.

Suppose you want certain devices to be “chargeable” or “connectable” via USB.

interface Chargeable {
void charge();
}

interface Connectable {
void connect();
}

class Smartphone implements Chargeable, Connectable {


@Override
public void charge() {
[Link]("Smartphone is charging.");
}

@Override
public void connect() {
[Link]("Smartphone is connected.");
}
}

Here Smartphone can implement multiple interfaces,making it chargeable and connectable


even if it also extends some other class.
2). a).
 Encapsulation is an Object-Oriented Programming (OOP) concept that involves wrapping
data and methods together in a single unit called a class and restricting direct access to
the data.

 In java data encapsulation is achieved by declaring a class variable as private and


providing public getter and setter methods to access and modify those variables in a
controlled way

 Encapsulation ensures data hiding, controlled access, and better code maintainability ,
making Java programs more secure and reliable.

class Student {

private String name;


private String studentId;
private double grade;

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public String getStudentId() {


return studentId;
}

public void setStudentId(String studentId) {


[Link] = studentId;
}

public double getGrade() {


return grade;
}

public void setGrade(double grade) {


if (grade >= 0 && grade <= 100) { // validation
[Link] = grade;
} else {
[Link]("Invalid grade!");
}
}
}

public class Main {


public static void main(String[] args) {
Student student = new Student();

[Link]("Isaac");
[Link]("CS1023");
[Link](85.5);

[Link]("Name: " + [Link]());


[Link]("Student ID: " + [Link]());
[Link]("Grade: " + [Link]());
}
}

b).

A constructor is a special method used to initialize objects when they are created and then
automatically called when an object is instantiated using the new keyword.

class Book {
String title;
String author;
double price;
int yearOfPublication;

public Book(String title, String author, double price, int yearOfPublication) {


[Link] = title;
[Link] = author;
[Link] = price;
[Link] = yearOfPublication;
}

public void displayBookInfo() {


[Link]("Title: " + title);
[Link]("Author: " + author);
[Link]("Price: $" + price);
[Link]("Year of Publication: " + yearOfPublication);
}

public static void main(String[] args) {

Book book = new Book("Clean Code", "Robert C. Martin", 45.99, 2008);


[Link]();
}
}

3) a).
Method overloading occurs when multiple methods in the same class have the same name
but different parameter lists while method overriding occurs when a subclass provides a
specific implementation of a method already defined in its superclass

Example of method overloading


class Calculator {

int add(int a, int b) {


return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}

double add(double a, double b) {


return a + b;
}
}

Example of method overriding.


class Animal {
void makeSound() {
[Link]("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
void makeSound() {
[Link]("Dog barks");
}
}

b).
// Base class
class Person {
protected String name;

public Person(String name) {


[Link] = name;
}

public void getRole() {


[Link]("I am a person.");
}
}

// Subclass Student
class Student extends Person {
public Student(String name) {
super(name);
}

@Override
public void getRole() {
[Link](name + " is a student.");
}
}

// Subclass Instructor
class Instructor extends Person {

public Instructor(String name) {


super(name);
}

@Override
public void getRole() {
[Link](name + " is an instructor.");
}
}

// Main class
public class Main {
public static void main(String[] args) {

// Array of Person references


Person[] people = new Person[3];
people[0] = new Person("Alex");
people[1] = new Student("Isaac");
people[2] = new Instructor("Dr. Smith");

// Demonstrating polymorphism
for (Person person : people) {
[Link](); // Calls the overridden method at runtime
}
}
}
4). a). Event-driven programming is a programming model in which the flow of program
execution is determined by events rather than by a fixed sequence of instructions. An event is
any action or occurrence detected by the program such as a mouse-click.

Example: Clicking on a Login page.

import [Link].*;
import [Link].*;

public class LoginExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Login");
JButton loginButton = new JButton("Login");

// Event listener
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Login button clicked!");
}
});

[Link](loginButton);
[Link](200, 150);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
b).
import [Link].*;
import [Link];
import [Link];

public class EvenOddChecker {

public static void main(String[] args) {

// Create frame
JFrame frame = new JFrame("Even or Odd Checker");

// Create components
JTextField textField = new JTextField();
JButton button = new JButton("Check");
JLabel label = new JLabel("Enter a number and click Check");

// Set bounds (simple layout)


[Link](50, 30, 200, 30);
[Link](100, 70, 100, 30);
[Link](50, 110, 250, 30);

// Add action listener to button


[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
int number = [Link]([Link]());

if (number % 2 == 0) {
[Link]("The number is EVEN");
} else {
[Link]("The number is ODD");
}
} catch (NumberFormatException ex) {
[Link]("Please enter a valid integer");
}
}
});

// Add components to frame


[Link](textField);
[Link](button);
[Link](label);

[Link](320, 200);
[Link](null);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
5). a).
A package in java is a namespace that groups related classes,interfaces and sub-packages
[Link] help in organization of large java programs into logical units making it easier
for them to maintain, reuse and develop.

 Packages improve code organization by grouping related functionality


 They enable avoidance of name conflicts since classes with same names can exist in
different packages.
 Packages can be reused in different projects as it encourages clean APIs and shared
libraries.

b).
import [Link];

// Interface Shape
interface Shape {
double area();
double perimeter();
}

// Class Triangle implementing Shape


class Triangle implements Shape {
private double a, b, c; // sides

public Triangle(double a, double b, double c) {


this.a = a;
this.b = b;
this.c = c;
}

@Override
public double area() {
double s = (a + b + c) / 2; // semi-perimeter
return [Link](s * (s - a) * (s - b) * (s - c));
}

@Override
public double perimeter() {
return a + b + c;
}
}

// Class Circle implementing Shape


class Circle implements Shape {
private double radius;

public Circle(double radius) {


[Link] = radius;
}

@Override
public double area() {
return [Link] * radius * radius;
}

@Override
public double perimeter() {
return 2 * [Link] * radius;
}
}

// Main class
public class ShapeDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Triangle input
[Link]("Enter the sides of the triangle:");
double side1 = [Link]();
double side2 = [Link]();
double side3 = [Link]();

Shape triangle = new Triangle(side1, side2, side3);


[Link]("Triangle area: " + [Link]());
[Link]("Triangle perimeter: " + [Link]());

// Circle input
[Link]("\nEnter the radius of the circle:");
double radius = [Link]();

Shape circle = new Circle(radius);


[Link]("Circle area: " + [Link]());
[Link]("Circle perimeter: " + [Link]());

[Link]();
}
}

You might also like