0% found this document useful (0 votes)
14 views

My notes OOP exam notes

Open book exam uni maastricht

Uploaded by

dominik.gorak
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)
14 views

My notes OOP exam notes

Open book exam uni maastricht

Uploaded by

dominik.gorak
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
You are on page 1/ 14

Add headings (Format > Paragraph styles) and they will appear in your table of contents.

1. Objects and classes

1.1. Instance fields


Instance fields are variables that belong to each different individual instance of an
object of a class.

Static fields belong to all the objects of the class.

1.2. Abstract classes and interfaces

1
Feature Abstract Class Interface
Instantiation Cannot be instantiated directly. Cannot be instantiated directly.
Supports single inheritance (a
class can extend only one abstract Supports multiple inheritance (a class can
Inheritance class). implement multiple interfaces).
Methods Can have: Can have:
- Abstract methods (no body). - Abstract methods (implicitly public abstract).
- Default methods (instance methods with a
- Concrete methods (with body). body, introduced in Java 8).
- Static methods (with body, introduced in Java
- Static methods (with body). 8).
- Private methods (helper methods, introduced
in Java 9).
Can have instance fields and static Can only have public static final fields
Fields fields. (constants).
Can have constructors, but only to
initialize fields or setup logic for
Constructors subclasses. Cannot have constructors.
Access Methods can have any access
Modifiers modifier (public, protected, Methods are implicitly public unless explicitly
(Methods) private). private (allowed for helper methods in Java 9).
Access
Modifiers Fields can have any access
(Fields) modifier. Fields are implicitly public static final.
Inheritance Use the extends keyword for Use the implements keyword for
Keyword inheritance. implementation.
Static Methods Allowed, with a body. Allowed, with a body (introduced in Java 8).
Default
Methods Not allowed. Allowed (introduced in Java 8).
Best for base classes that provide
partial or complete Best for defining behavior contracts that
Use Case implementation. unrelated classes can implement.
Multiple Not supported (class can extend Supported (class can implement multiple
Inheritance only one abstract class). interfaces).
Type of
Relationships Defines an "is-a" relationship. Defines a "can-do" or "capable-of" relationship.

Interface to class CODE:

// Interface definition
interface Measurable {
double getMeasure(); // Interface method
}

2
// Class implementing the interface
class Coin implements Measurable {
private double value;
private String name;

// Constructor
public Coin(double value, String name) {
this.value = value;
this.name = name;
}

// Implementation of getMeasure (returns the coin value)


@Override
public double getMeasure() {
return value;
}

// Additional class-specific method


public String getName() {
return name;
}
}

// Class to store Measurable objects


class DataSet {
private Measurable[] data;
private int size;

public DataSet() {
data = new Measurable[10];
size = 0;
}

// Method to add an object implementing Measurable


public void add(Measurable obj) {
if (size < data.length) {
data[size++] = obj;
}
}

// Method to get the maximum measurable value


public Measurable getMaximum() {
if (size == 0) return null;
Measurable max = data[0];
for (int i = 1; i < size; i++) {
if (data[i].getMeasure() > max.getMeasure()) {
max = data[i];

3
}
}
return max;
}
}

// Main class
public class Main {
public static void main(String[] args) {
// Create a DataSet object
DataSet coinData = new DataSet();

// Add Coin objects to the dataset


coinData.add(new Coin(0.25, "Quarter"));
coinData.add(new Coin(0.05, "Nickel"));
coinData.add(new Coin(1.00, "Dollar"));

// Get the maximum measurable object


Measurable max = coinData.getMaximum();

// Casting from interface (Measurable) to class (Coin)


if (max instanceof Coin) { // Ensure safe casting
Coin maxCoin = (Coin) max;
String name = maxCoin.getName(); // Accessing class-specific method
System.out.println("The coin with the maximum value is: " + name);
}
}
}

4
public class Meal implements Measurable{
private String name;
private int price;

public Meal(String name, int price){


this. name = name;
this. price = price;
}
public int getPrice() {
return price;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Meal [name=" + name + ", price=" + price + "]";
}

public class Item implements Measurable {

5
private String name;
private int price;
private int barCode;

public Item(String name, int price, int barCode){


this. name = name;
this. price = price;
this. barCode = barCode;
}

public int getBarCode() {


return barCode;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}

public interface Measurable {


int getPrice();
}

import java.util.ArrayList;

public class Main {


public static void main(String[] args) {
ShoppingBag shop = new ShoppingBag();
Meal meal = new Meal("Spaghetti", 20);
Item shampoo = new Item("Shampoo", 5, 123);
shop.addItem(meal);
shop.addItem(shampoo);
int maxValue = Integer.MIN_VALUE;
Measurable maxPrice = null;
for(Measurable m : shop.getShoppingBag()){
if(maxValue<m.getPrice()) {maxValue = m.getPrice(); maxPrice = m;}

6
System.out.println(maxPrice instanceof Meal);
ArrayList<Object> a = new ArrayList<>();
a.add(maxPrice);
System.out.println(a.get(0).toString());
}
}

import java.util.*;

public class ShoppingBag {


private ArrayList<Measurable> shoppingList;

public ShoppingBag(){
this.shoppingList = new ArrayList<Measurable>();
}

public void addItem(Measurable item)


{
shoppingList.add(item);
}
public ArrayList<Measurable> getShoppingBag()
{
return shoppingList;
}

Lab 6
1) Reading file to find number of words, lines and chars
import java.io.*;

public class FileCounter {

// int for the number of letters


private static int chars = 0;
// int for the number of words
private static int words = 0;
// int for the number of lines
private static int lines = 0;

7
public static void processFile(String fileName) {
// reset counters
chars = 0;
words = 0;
lines = 0;

try {
// open file stream
BufferedReader br = new BufferedReader(new FileReader(fileName));

// read file line by line


while (true) {
String line = br.readLine();
if (line == null) {
break;
}

// increase line count


lines++;

// count words
String[] wordsInLine = line.split(" ");
words += wordsInLine.length;

// count characters (includes spaces!)


chars += line.length();
}

// close file stream


br.close();
} catch (IOException e) {
System.out.println(e);
}
}

public static int getWordCount() {


return words;
}

public static int getCharacterCount() {


return chars;
}

public static int getLineCount() {


return lines;

8
}

public static void main(String[] args) {


String fileName = "Solution/file1.txt";
processFile(fileName);
System.out.println("File " + fileName + " has:");
System.out.println(getWordCount() + " words");
System.out.println(getCharacterCount() + " characters");
System.out.println(getLineCount() + " lines");
}
}

2) Program “Find” that finds all the lines with a keyword

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Find {

public static String[] getLinesWithWordForFile(String file, String word) {


List<String> lines = new ArrayList<String>();

try {
// open file stream
BufferedReader br = new BufferedReader(new FileReader(file));

// read file line by line


while (true) {
String line = br.readLine();
if (line == null) {
break;
}

// check if line contains word


if (line.contains(word)) {
lines.add(line);
}
}

// close file stream

9
br.close();
} catch (IOException e) {
System.out.println(e);
}

// convert List<String> to String[]


return lines.toArray(new String[lines.size()]);
}

public static void main(String[] args) {


for (int i = 1; i < args.length; i++) {
String[] lines = getLinesWithWordForFile(args[i], args[0]);
for (String line : lines) { // printing String[] does not work!
System.out.println(args[i] + ": " + line); }
}
}
}

3) Modify BankAccount so it throws an “IllegalArgumentException” = negative balance, amount is negative/ not in


range of 0 – balance (CATCH all three)

public class BankAccount {

private double balance;


public BankAccount(double initialBalance) {
if (initialBalance < 0) {
throw new IllegalArgumentException("Initial balance cannot be negative.");
}
balance = initialBalance;
}
public void deposit(double amount) {
if (amount < 0) {
throw new IllegalArgumentException("Cannot deposit a negative amount.");
}
double newBalance = balance + amount;
balance = newBalance;
}
public void withdraw(double amount) {
if (amount < 0) {
throw new IllegalArgumentException("Cannot withdraw a negative amount.");
}
double newBalance = balance - amount;

if (newBalance < 0) {

10
throw new IllegalArgumentException("Cannot withdraw more than the current
balance.");
}
balance = newBalance;
}
public double getBalance() {
return balance;
}
}

MOUSE LISTENER RETURNS the coordinates WHEN I CLICKED IT,


WHEN I release it, and when i exit the frame, so on.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MouseListenerExample extends JFrame implements MouseListener {


private JLabel label;

// Constructor
public MouseListenerExample() {
// Set up the JFrame
setTitle("MouseListener Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create a label
label = new JLabel("Mouse Event Tracker");
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setFont(new Font("Arial", Font.BOLD, 18));
add(label);

// Add MouseListener to the JFrame


addMouseListener(this);

setVisible(true);
}

@Override
public void mouseClicked(MouseEvent e) {
label.setText("Mouse clicked at: (" + e.getX() + ", " + e.getY() + ")");
}

11
@Override
public void mousePressed(MouseEvent e) {
label.setText("Mouse pressed at: (" + e.getX() + ", " + e.getY() + ")");
}

@Override
public void mouseReleased(MouseEvent e) {
label.setText("Mouse released at: (" + e.getX() + ", " + e.getY() + ")");
}

@Override
public void mouseEntered(MouseEvent e) {
label.setText("Mouse entered the frame.");
}

@Override
public void mouseExited(MouseEvent e) {
label.setText("Mouse exited the frame.");
}

public static void main(String[] args) {


new MouseListenerExample();
}
}

FLOWER DRAWING
import javax.swing.*;
import java.awt.*;

public class FlowerDrawing extends JPanel {

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

// Cast Graphics to Graphics2D for advanced drawing


Graphics2D g2d = (Graphics2D) g;

// Set background color


g2d.setColor(new Color(240, 248, 255)); // Light blue background
g2d.fillRect(0, 0, getWidth(), getHeight());

12
// Draw the flower
drawFlower(g2d, getWidth() / 2, getHeight() / 2, 100);
}

private void drawFlower(Graphics2D g2d, int x, int y, int size) {


int petalCount = 8; // Number of petals
int petalWidth = size / 3;
int petalHeight = size / 2;

// Draw petals
g2d.setColor(Color.PINK);
for (int i = 0; i < petalCount; i++) {
double angle = Math.toRadians((360.0 / petalCount) * i);
int petalX = (int) (x + Math.cos(angle) * size / 2) - petalWidth / 2;
int petalY = (int) (y + Math.sin(angle) * size / 2) - petalHeight / 2;

// Draw each petal as an oval


g2d.fillOval(petalX, petalY, petalWidth, petalHeight);
}

// Draw the flower center


g2d.setColor(Color.YELLOW);
int centerSize = size / 4;
g2d.fillOval(x - centerSize / 2, y - centerSize / 2, centerSize,
centerSize);

// Draw the stem


g2d.setColor(new Color(34, 139, 34)); // Forest green
g2d.fillRect(x - 5, y + size / 2, 10, size);
}

public static void main(String[] args) {


// Set up the JFrame
JFrame frame = new JFrame("Flower Drawing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);

// Add the flower panel


FlowerDrawing flowerPanel = new FlowerDrawing();
frame.add(flowerPanel);

frame.setVisible(true);
}
}

13
14

You might also like