Индивидуальная практическая работа №1. Обьекты и класcы
packagejava.di.rabota1;
classProduct { // описываем отдельный новый класс
publicStringname; // свойства класса:наименование продукции
publicdoublecost; // цена
publicbooleanavailability; // наличие в магазинe
/* конструктор с двумя параметрами (инициализация значений полей)*/
publicProduct(Stringname, doublecost) {
/* Ключевое слово this показывает, что необходимо текущему экземпляру класса присвоить значение, переданное в конструктор */
this.name = name;
this.cost = cost;
}
/* перегруженный конструктор с тремя параметрами*/
publicProduct(Stringname, doublecost,booleanavailability) {
this(name,cost);
this.availability = availability;
}
/*метод класса выводит на экран наименование продукции и стоимость*/
publicvoidprintProduct() {
System. out. println("Продукция - " + name + "; цена - " + cost + " руб за кг.");
}
/* метод класса выводит на экран наличие товара*/
publicvoidavailabilityProduct(booleanavailability) {
if (availability) System. out. println("Продукция - " + name + "; цена - " + cost + " руб за кг - есть в наличии");
elseSystem. out. println("Продукции нет в наличии");
}
}
publicclassWriterInfo{
publicstaticvoidmain(String[] args) {
Product o1 = newProduct(“Мандарины”, 3.45); // Создаём объект
/*Определяемналичие, обращаясь к свойствуavailability */
o1.availability = true;
o1.printProduct(); // выводим на экран наим. продукции и цену
o1.availabilityProduct(availability:true);// выводим на экран наличие продукции
/* Создаём другой объект того же класса */
Product o2 = newProduct(“Бананы”, 2.35, false);
o2.printProduct();
o2.availabilityProduct(availability: false);
|
|
}
}
Индивидуальная практическая работа №2 Наследование и скрытие данных. Абстрактныеклассыиинтерфейсы
packagejava.di.rabota2;
//Интерфейс:
public interface Production {
void print();
intpercentage_def(int count,intcount_def);
// метод: расчет процента бракованной продукции
}
class Toys implements Production { // создаем класс реализующий интерфейс
String name;
intcount_def;
int count;
Toys(String name, int count, intcount_def){
this.name = name;
this.count = count;
this.count_def = count_def;
}
publicintpercentage_def(intcount,intcount_def) {
intrez = (count_def * 100) / count; // расчет процента брак. продукции
return rez;
}
public void print() {
System. out. printf("Игрушка '%s',обьемпродукции %d штук (количествобракованныхизделий %d штук) \n", name, count, count_def);
}
}
// создаем второй класс реализующий интерфейс
public class TV implements Production {
String name;
int count;
intcount_def;
TV(String name,intcount,intcount_def) {
this.name = name;
this.count = count;
this.count_def = count_def;
}
publicintpercentage_def(intcol,intcol_def) {
intrez = (col_def*100)/col;
System. out. printf("Процентбракованныхизделий " +
"впродукциителевизор '%s' - %d процентов. \n", name, rez);
return rez;
}
public void print() { System. out. printf(" Телевизор '%s',обьемпродукции %d штук" +" (количествобракованныхизделий %d штук.) \n", name, col, col_def);
}
}
// создаем второй класс, который выводит информацию о продукте
import java.util.Scanner; // импортируем класс Scannerpublic class SearchInfo {
public static void main(String[] args) {
Scanner in = new Scanner(System. in);
System. out. println("Введитепроцентбракованнойпродукции: ");
int input = in.nextInt();// возвращает следующее случайное значение типа int
System. out. println("Your input is: " + input);
SearchInfo. search (input);
Production toy1 = new Toys("Кукла", 70, 5);
Production toy2= new Toys("Конструктор", 40, 4);
int rezult1 = toy1.percentage_def(70,5);
if(rezult1>input) {// сравнение с процентом брака
toy1.print();
System. out. printf("Процентбрака %d процентов. \n", rezult1);
}
int rezult2 = toy2.percentage_def(40,4);
if(rezult2>input) {
toy2.print();
System. out. printf("Процентбрака - %d процентов. \n", rezult2);
}
Production tv1 = new TV("Горизонт", 100, 9);
Production tv2 = new TV("Горизонт", 80, 4);
int rezult1 = tv1.percentage_def(100,9);
if(rez3>input) {
tv1.print();
}
|
|