Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
DynamicIntArray, который реализует функционал динамического массива целых чисел.public String errMessage;
private AccountBalance balance;
private boolean isError(byte status) {}
public class Account {}public class Account {
private double balance;
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}Cart cart = new Cart();
cart.addItem(new Item("Клавиатура", 2000));public class Cart {
private Item[] stack; // массив для реализации стека
private int topIndex; // указатель на вершину стека
// При создании корзины мы должны
// указать максимальное количество элементов
// в корзине
public Cart(int capacity) {
stack = new Item[capacity];
topIndex = -1;
}
// Добавление нового товара в корзину
public boolean addItem(Item item) {
return push(item);
}
// Приватный метод, который реализует добавление в стек
private boolean push (Item item) {
// Добавляем товар в стек
return true; // или false если не стек переполнен
}
// Удаление последнего добавленного товара в корзину
public Item deleteLastAddedItem() {
return pop();
}
// Приватный метод, который реализует извлечение из стека
private Item pop() {
return new Item(); // Извлеченный из стека товар
}
}Cart cart = new Cart();
cart.addItem(new Item("Клавиатура", 2000));
// Данная инструкция вызовет ошибку компиляции
cart.topIndex = 4;distanceFromOrigin() должны учитывать координату z и возвращать расстояние по формуле .public class Box {
double width;
double height;
double depth;
}class Vehicle {}
class Car extends Vehicle {}class MyClass {
public void foo() {
// ... код
}
public void foo(String s) {
// ... код
}
}transactionFeepublic void subtract(TimeSpan span)public void scale(int factor)// Каждый объект класса BankAccount представляет данные одного
// счета пользователя, включая имя и баланс счета
public class BankAccount {
String name;
double balance;
public void deposit(double amount) {
balance = balance + amount;
}
public double getBalance() {
return this.balance;
}
public boolean withdraw(double amount) {
balance = balance - amount;
return true;
}
}public boolean transfer(BankAccount receiver, double amount)class FileManager {
public void saveToFile(String text, String path) {
// тело метода
}
}
class Document {
// класс Document содержит ссылку на объект
// класса FileManager
private FileManager manager;
private StringBuilder contents;
private String path;
public Document(FileManager manager, String path) {
this.manager = manager;
this.contents = new StringBuilder();
this.path = path;
}
public void saveDocument() {
manager.saveToFile(contents.toString(), path);
}
}// Суперкласс
class Person {
String firstName;
String lastName;
}
// Подкласс
class Student extends Person {
String group;
long id;
}
public class Main {
public static void main(String[] args) {
Student student = new Student();
student.firstName = "Иван";
student.lastName = "Иванов";
student.id = 10000L;
}
}// Суперкласс
class Person {
String firstName;
String lastName;
}
class UniversityMember{}
// МНОЖЕСТВЕННОЕ НАСЛЕДОВАНИЕ ЗАПРЕЩЕНО!
// ЭТОТ КОД ВЫЗОВЕТ ОШИБКУ КОМПИЛЯТОРА
class Student extends Person, UniversityMember {
String group;
long id;
}class Vehicle {
public void moveTo(Point destination) {
// тело метода
}
}
class Truck extends Vehicle {
public void carryWeight(double weight) {
// тело метода
}
}
class DumpTruck extends Truck {
public void dumpWeight() {
// тело метода
}
}class Shape2D {
private double width;
private double height;
}
class Rectangle extends Shape2D {
// ОШИБКА НА ЭТАПЕ КОМПИЛЯЦИИ
public double getArea() {
return width * height;
}
}class Shape2D {
protected double width;
protected double height;
}
class Rectangle extends Shape2D {
// Данный код корректен
public double getArea() {
return width * height;
}
}class Shape2D {
private double width;
private double height;
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
}
class Rectangle extends Shape2D {
// Данный код корректен
public double getArea() {
return getWidth() * getHeight();
}
}class Animal {
public Animal() {
System.out.println("Конструктор класса Animal");
}
}
class Mammal extends Animal {
public Mammal() {
System.out.println("Конструктор класса Mammal");
}
}
class Cat extends Mammal {
public Cat() {
System.out.println("Конструктор класса Cat");
}
}
public class Main {
public static void main(String[] args) {
Cat cat = new Cat();
}
}Конструктор класса Animal
Конструктор класса Mammal
Конструктор класса Catpublic class Main {
public static void main(String[] args) {
Box3D box = new Box3D(100);
}
}
class Box {
public double width;
public double height;
public Box(double width, double height) {
this.width = width;
this.height = height;
}
}
class Box3D extends Box {
public double depth;
// НЕТ ЯВНОГО ВЫЗОВА КОНСТРУКТОРА СУПЕРКЛАССА !
public Box3D(double depth) {
this.depth = depth;
}
}public class Main {
public static void main(String[] args) {
Box3D box = new Box3D(100, 200, 300);
}
}
class Box {
public double width;
public double height;
public Box(double width, double height) {
this.width = width;
this.height = height;
}
}
class Box3D extends Box {
public double depth;
public Box3D(double width, double height, double depth) {
super(width, height); // <-- ВЫЗОВ КОНСТРУКТОРА СУПЕРКЛАССА
this.depth = depth;
}
}class Box {
private double width;
private double height;
public Box(double width, double height) {
this.width = width;
this.height = height;
}
// Площадь прямоугольника
public double getArea() {
return width * height;
}
}
class Box3D extends Box {
private double depth;
public Box3D(double width, double height, double depth) {
super(width, height); // <-- ВЫЗОВ КОНСТРУКТОРА СУПЕРКЛАССА
this.depth = depth;
}
// Мы используем метод суперкласса, чтобы
// посчитать площадь трехмерной коробки
public double get3DArea() {
double area2D = super.getArea(); // <---- Вызов метода суперкласса
return area2D * depth;
}
}public class Main {
public static void main(String[] args) {
Box3D box = new Box3D(100, 200, 300);
System.out.println(box.getInfo());
}
}
class Box {
private double width;
private double height;
public Box(double width, double height) {
this.width = width;
this.height = height;
}
public String getInfo() {
return "Объект Box {" +
"ширина = " + width +
", высота = " + height +
'}';
}
}
class Box3D extends Box {
private double depth;
public Box3D(double width, double height, double depth) {
super(width, height);
this.depth = depth;
}
}Объект Box {ширина = 100.0, высота = 200.0}Box3D box = new Box3D(100, 200, 300);
System.out.println(box.getInfo());class Box3D extends Box {
private double depth;
public Box3D(double width, double height, double depth) {
super(width, height);
this.depth = depth;
}
public String get3DInfo() {
return "Объект Box3D {" +
"ширина = " + super.getWidth() +
", высота = " + super.getHeight() +
", глубина = " + depth +
'}';
}
}class Box {
private double width;
private double height;
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public Box(double width, double height) {
this.width = width;
this.height = height;
}
public String getInfo() {
return "Объект Box {" +
"ширина = " + width +
", высота = " + height +
'}';
}
}public class Main {
public static void main(String[] args) {
Box3D box = new Box3D(100, 200, 300);
System.out.println(box.get3DInfo());
}
}Объект Box3D {ширина = 100.0, высота = 200.0, глубина = 300.0}public class Main {
public static void main(String[] args) {
Box box = new Box(600,600);
System.out.println(box.getInfo());
Box3D box3D = new Box3D(100, 200, 300);
System.out.println(box3D.getInfo());
}
}
class Box {
// Поля, конструктор и геттеры\сеттеры
public Box(double width, double height) {
this.width = width;
this.height = height;
}
public String getInfo() {
return "Объект Box {" +
"ширина = " + width +
", высота = " + height +
'}';
}
}
class Box3D extends Box {
// Поля, конструктор и геттеры\сеттеры
@Override
public String getInfo() {
return "Объект Box3D {" +
"ширина = " + super.getWidth() +
", высота = " + super.getHeight() +
", глубина = " + depth +
'}';
}
}Объект Box {ширина = 600.0, высота = 600.0}
Объект Box3D {ширина = 100.0, высота = 200.0, глубина = 300.0}Box box = new Box(600, 600);
System.out.println(box.getInfo());
Box3D box3D = new Box3D(100, 200, 300);
System.out.println(box3D.getInfo());final class A {}
class B extends A {
// ВЫЗОВЕТ ОШИБКУ КОМПИЛЯЦИИ !
}
class C {
final public void foo() {}
}
class D extends C {
@Override
public void foo() {} // <-- Ошибка компиляции !
}public class Main {
public static void main(String[] args) {
Box box = new Box();
System.out.println(box.toString());
}
}
class Box{}com.company.Box@1540e19dpublic class Main {
public static void main(String[] args) {
Box box = new Box(100, 200);
System.out.println(box.toString());
}
}
class Box {
private double width;
private double height;
public Box(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public String toString() {
return "Box{" +
"width=" + width +
", height=" + height +
'}';
}
}Box{width=100.0, height=200.0}public class Main {
public static void main(String[] args) {
Box box = new Box(100, 200);
System.out.println(box.toString());
System.out.println(box);
}
}Box{width=100.0, height=200.0}
Box{width=100.0, height=200.0}// ДАННЫЙ КОД ВЫЗОВЕТ ОШИБКУ КОМПИЛЯЦИИ!
class MyClass {
public int foo() {
return 0;
}
public double foo() {
return 0;
}
}class MyClass {
public MyClass() {
// какой-то код
}
public MyClass(int arg0) {
// какой-то код
}
public MyClass (int arg0, String arg1) {
// какой-то код
}
}class MyClass {
public MyClass() {
// Вызываем конструктор MyClass(int arg0)
this(0);
}
public MyClass(int arg0) {
// Вызываем конструктор MyClass (int arg0, String arg1)
this(arg0, " ");
}
public MyClass(int arg0, String arg1) {
// какой-то код
}
}CarWheel
class Car {
private Wheel[] wheels;
public Car() {
this.wheels = new Wheel[4];
}
}
class Wheel {}public class Human {
private String name; // private это "-"
Boolean gender = true; // default это "~"
protected long chromosome; // protected это "#"
public int age; // public это "+"
// Статические атрибуты подчеркиваются
public static long dna;
// Константы можно отобазить как readOnly
final int SECRET = 924;
/* Как правило, конструкторы
* изображаются как обычные методы */
public Human() {}
public Human (String name) {this.name = name;}
/* Методы отображаются как
* [-~#+]имя(тип_аргументов): возвращаемый тип
* Например: public String foo (int a, double b)
* будет +foo(int, double): String */
public void breath() {}
private void sleep(int hours) {}
protected boolean sneeze() { return true; }
int run (int speed, String direction) { return 0; }
public static int calculateAge() { return 0; }
}Человек <фамилия> <имя>, возраст: <возраст>Студент группы <группа>, <фамилия> <имя>, возраст: <возраст>. Номер студенческого билета: <номер>Преподаватель кафедры <кафедра>, <фамилия> <имя>, возраст: <возраст>. Зарплата: <зарплата>public class Main {
public static void main(String[] args) {
Box myBox = new Box();
}
}myBox.width = 100;public class Main {
public static void main(String[] args) {
// Создаем объект типа Box
Box myBox = new Box();
// Присваиваем значения переменным экземпляра myBox
myBox.width = 10;
myBox.height = 20;
myBox.depth = 15;
// Рассчитываем объем коробки
double volume = myBox.width * myBox.height * myBox.depth;
System.out.println("Объем равен: " + volume);
}
}public class Box {
double width;
double height;
double depth;
}public class Main {
public static void main(String[] args) {
Box myBox1 = new Box();
Box myBox2 = new Box();
// Присваиваем значения для mybox1
myBox1.width = 10;
myBox1.height = 20;
myBox1.depth = 15;
// Присваиваем значения для mybox2
myBox2.width = 3;
myBox2.height = 6;
myBox2.depth = 9;
double volume;
// объем первой коробки
volume = myBox1.width * myBox1.height * myBox1.depth;
// будет выведено 3000
System.out.println("Объем равен: " + volume);
// объем второй коробки
volume = myBox2.width * myBox2.height * myBox2.depth;
// будет выведено 162
System.out.println("Объем равен: " + volume);
}
}Объем равен: 3000.0
Объем равен: 162.0[возвращаемый тип] имя ([список параметров]) {
[тело метода]
}class Box {
double width;
double height;
double depth;
void getVolume() {
System.out.print("Объем коробки равен ");
System.out.println(width * height * depth);
}
}mybox1.volume();
mybox2.volume();public class NameSorter implements Comparator {
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof Student && o2 instanceof Student) {
Student s1 = (Student) o1;
Student s2 = (Student) o2;
return s1.getName().compareTo(s2.getName());
}
return 0;
}
}







public class Sums {
public static void sum(BufferedReader in){
// Программа получает последовательность целых чисел на вход
// и возвращает сумму этих чисел
int s, nextInt;
s = 0;
System.out.println("Пожалуйста, введите последовательность чисел, для окончания ввода, введите 0");
nextInt = Integer.parseInt(in.readLine());
// Читаем следующее значение. Ожидаем целое число
while (nextInt!=0) {
s = s + nextInt;
nextInt = Integer.parseInt(in.readLine());
}
System.out.println("Сумма равна " + s);
}
public static void main(String[] arg) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// in будет получать данные из стандартного входного потока
System.out.println("Вы хотите посчитать сумму чисел? (y/n)");
String c = in.readLine();
// Проверяем правильность ввода
// Если ввод некорректен - просим повторить снова
while (!c.equals("y") && !c.equals("n")) {
System.out.println("Пожалуйста, повторите ввод (y/n)");
c = in.readLine();
}
while (c.equals("y")) {
sum(in); // Функция для ввода и подсчета суммы чисел
System.out.println("Вы хотите посчитать сумму еще раз? (y/n)");
c = in.readLine();
while (!c.equals("y") && !c.equals("n")) {
System.out.println("Пожалуйста, повторите ввод (y/n)");
c = in.readLine();
}
}
System.out.println("Программа заканчивает работу.");
}
}import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class ListOfNumbers {
private List<Integer> list;
private static final int LIST_SIZE = 10;
public ListOfNumbers() {
list = new ArrayList<>(LIST_SIZE);
for (int i = 0; i < list.size(); i++)
list.add(i);
}
public void writeList() {
PrintWriter out = null;
try {
System.out.println("Entering try statement");
out = new PrintWriter(new FileWriter("OutFile.txt"));
for (int i = 0; i < list.size(); i++)
out.println("Value at: " + i + " = " + list.get(i));
} catch (IndexOutOfBoundsException e) {
System.err.println("Caught IndexOutOfBoundsException: " +
e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
}
}

