Programming Java

Tasks studies - laboratory


Project maintained by dawidolko Hosted on GitHub Pages — Theme by dawidolko

OBJECT-ORIENTED JAVA PROGRAMMING – LABORATORY

INHERITANCE

COMPOSITION

Conceptually, composition means that “an object is contained within another object”.

It is a “whole-part” relationship (B “contains” A). For example, Vehicle objects contain objects of type Size, Wheels, Engine, etc. Composition is achieved by defining fields in a new class that are objects of existing classes.


labo2

package PO_UR.Lab06.Composition;
public class Person {
String name, last name;
public Person(String name, String last name) {
this.name = first name;
this.last name = last name;
}
public String getName() {
return name;
}
public String getLastName() {
return lastName;
}
}
package PO_UR.Lab06.Composition;
public class Book {
Person author;
String title;
double price;
public Book(Person author, String title, int i, double price) {
this.author = author;
this.title = title;
this.price = price;
}
public Person getAuthor() {
return author;
}
public String getTitle() {
return title;
}
public double getPrice() {
return price;
}
}
package PO_UR.Lab06.Composition;
public class Main {
public static void main(String[] args) {
Book k1 = new Book(new
Person("Henryk","Sienkiewicz"),"Deluge",32,50);
}
}

INHERITANCE

Inheritance is one of the basic mechanisms of object-oriented programming. This mechanism allows defining new classes based on existing ones.

Inheritance is a ubiquitous and extremely powerful mechanism in Java. Almost every class, or to be more precise, every class except the java.lang.Object class - inherits from some other class, because each class implicitly inherits from the aforementioned Object class.

There is NO multiple inheritance in Java - a class can directly inherit only one class.

Inheritance - similarly to composition (and even to a greater extent) - allows reducing coding costs (reusing). This is also a reflection of natural situations.

Inheritance consists in taking over the properties and functionality of objects of another class and possibly modifying these properties and functionality in such a way that they are more specialized.

This is a relationship called generalization-specialization: B “is of type” A, “B is A”, and at the same time B specializes A. A is a generalization of B.

package PO_UR.Lab06.Inheritance;
public class Employee {
String name, last name;
int salary;
public Employee() {
name = " ";
last name = " ";
salary = 0;
}
public Employee(String name, String last name, int salary) {
this. name = first name;
this. last name = last name;
this. salary = salary;
}
}
package PO_UR.Lab06.Inheritance;
public class Boss extends Employee{
int bonus;
public Boss(String name, String surname, int salary, int bonus) {
super(name, surname, salary);
this.premia = bonus;
}
}
package PO_UR.Lab06.Inheritance;
public class Company {
public static void main(String args[]){
Employee employee = new Employee("Wlodek", "Zięba", 3000);
System.out.println("Name: "+employee.name);
System.out.println("Surname: "+employee.surname);
System.out.println("Salary: "+employee.salary+"\n");
//first, let's create an object of the Boss class using the default

constructor
Boss boss = new Boss("jan","kowalki",12345,1);
//let's see what the appropriate fields look like
System.out.println("Name: "+boss.name);
System.out.println("Surname: "+boss.lastname);
System.out.println("Payout: "+boss.salary);
System.out.println("Bonus: "+boss.bonus+"\n");
//now we set the boss's data
boss.name = "Tadeusz";
boss.lastname = "Kowalski";
boss.salary = 10000;
boss.bonus = 2000;
System.out.println("Name: "+boss.name);
System.out.println("Surname: "+boss.lastname);
System.out.println("Payout: "+boss.salary);
System.out.println("Bonus: "+boss.bonus);
}
}

OBJECT CASTING, TYPE STATEMENT

A cast is an operation that changes a reference variable of one type to a reference variable of another type. In Java, there are two types of object casting: • upcasting – safe, • downcasting – requires testing (stating the type of the object instance).

The instanceof operator is used to determine the type of a reference ref instanceof T

In this case: • the expression null instanceof any_type always has the value false, • the expression x instanceof T will be syntactically incorrect (a compilation error will occur) if the type of reference x and type T are not related by an inheritance relationship, • the expression x instanceof T will have the value false if the actual type of reference x is a supertype of type T. Example

//upcasting
Boss manager = new Boss(); Employee work = (Boss) manager; // upcast Boss -> Employee
//downcast
Employee pra1 = (Employee) new Boss();
if(pra1 instanceof Boss){ //spr before casting
Boss boss = (Boss) pra1; //downcast employee to boss
}

OVERRIDING METHODS IN INHERITANCE

It is easy to imagine a situation in which a method with the same signature appears in both a base class and a derived class. In this situation, we say that the derived class overrides a method from the base class. Please see the example below. In the employee class we have a method:

public void Print(){
System.out.println("I am an employee, my data: \tName: "+name+"
\tLastname: "+lastname+" \tSalary: "+salary);

}

In the boss class

public void Print(){
System.out.println("I am a boss, my data: \tName: "+name+"
\tLastname: "+lastname+" \tSalary: "+salary);
System.out.println("I also have bonuses: "+bonus);

}
call:
employee.Print();

boss.Print(); result:
I am an employee, my data: Name: Wlodek Surname: Zięba
Pay: 3000
I am a boss, my data: Name: jan Surname: kowalki Pay: 12345
In addition, I have bonuses: 1
Modification of the method in the Boss class using the super method
public void Print(){
super.Print();
System.out.println("In addition, I have bonuses: "+bonus);
}

Tasks to solve on your own:

Task 1.

  1. Turn on the environment.

  2. Create a project containing the Main functions.

  3. Create a Point class that contains public fields (coordinates): x and y.

  4. For the Point class, define a parameterless constructor that will initialize the initial values ​​of the attributes.

  5. Define a second constructor that will remember the passed parameters as the values ​​of the attributes: x and y.

  6. Define the following methods for the point class: • getters and setters • void zero(); • void description(); • void move(int x, int y);
  7. In the main() method, create three Point objects.

  8. Show how to use each of the defined methods.

  9. Add the Figure, Rectangle and Triangle files to the package (provided by the instructor).

  10. Create Figure, Rectangle and Triangle objects. Check the operation of selected methods for the created objects.

  11. Design a Circle class containing fields: • center of the Point class – the center of the circle, • radius of type double and methods: • getPowierzchnia() returning the surface area, • getSrednica() returning the diameter • setRadius(double p) setting a new radius • getRadius() returning the radius • wSrodku(Point) checking whether a given point is inside the circle. Use the pattern:
( ) ( )
2 2 2
x a y b r − + −  , S a b = ( , )

Constructors: • Empty – initializing fields with default values ​​point (0,0), radius 0, • Specifying point and radius

  1. Modify the Rectangle and Triangle classes so that they inherit from the Figure class.

  2. Add an overloaded constructor for the Rectangle class in the form: Rectangle(float height,float width, String color). Inside the constructor, the constructor from the base class should be called.

  3. Add an overloaded constructor for the Triangle class in the form Triangle(float height,float base,String color).

  4. Add a method to move the rectangle by the given coordinates void move(float x, float y).

  5. For the Rectangle type object, call the move(3,5) method.

  6. Define a new Square class inheriting from the Rectangle class. Place getters and setters in it.

  7. Create any Square type object and give it any initial value.

  8. Override the description() methods in all classes.

  9. For the created objects, call the description() method, so that the description of the given object is displayed on the console.

  10. Modify the Circle class containing it so that it inherits from the Figure class.

  11. Check the operation of the defined methods for sample objects.

Task 2.

Write a program with two classes: Car and Passenger Car. These classes should contain the following fields: Car: Brand, Model, Body, Color, Year of production, Mileage (cannot be negative) Passenger Car: Weight (should be in the range of 2t–4.5t), Engine capacity (should be in the

range of 0.8-3.0), Number of people The Passenger Car class inherits from the Car class. In both classes, create a constructor that will retrieve data from the user. Additionally, in the Car class, overload the constructor in such a way that the field values ​​are method parameters. In the Car class, also create a method that displays information about the car. Override it in the CarCar class. In the Main() method, create an object of the CarCar class and two objects of the Car class (using different constructors). Display information about cars.

Task 3.

You should implement an application using: composition and inheritance, casting and the this operator and the super method for the following classes Bookstore, Textbook, Novel, Client, Book