A a1 = new A();
появляются во время работы программы (run time). Понимание этой разницы фундаментально важно!A a = new B();
(на которую компилятор, кстати, будет ругаться) происходят сразу две вещи: во-первых, создается экземпляр класса B, во-вторых, он приводится по типу к классу А (что возможно, ибо B унаследован от А, и значит, имеет, как минимум, все те же члены класса) и ссылка на него присваивается переменной типа A. Компилятор код проглотит, но будет ругаться именно на то, что это приведение типа происходит неявно. Правильнее было бы указать его явно, вот так: A a = (А) new B();
Если бы В не был унаследован от А, компилятор выдал бы в этом месте ошибку и ничего бы не скомпилировал.import java.util.Locale;
import java.time.LocalDate;
import java.time.temporal.WeekFields;
import java.time.DayOfWeek;
import static java.time.temporal.TemporalAdjusters.previousOrSame;
import static java.time.temporal.TemporalAdjusters.nextOrSame;
public class Main {
/**
* Determines first and last day of previous, current or following week from
* provided date according to the provided locale.<br/>
* <br/>
* <strong>NOTE</strong>: Although international standard ISO 8601 defines Monday as a first
* day of the week, several countries, including the United States, Canada,
* and Australia consider Sunday as the start of the week, and several other
* countries starts the week from Saturday.
*
* @param fromDate from which date the week offset should be calculated
* @param weekOffset offset in whole weeks, negative - previous, 0 - current, positive - following weeks
* @param locale locale defining which day should be considered a first day of week
* @return array of length 2, containing the dates of the first and last day of the week
*/
private static LocalDate[] getLocalizedWeekBoundary(LocalDate fromDate, long weekOffset, Locale locale) {
LocalDate[] result = new LocalDate[]{null,null};
DayOfWeek localizedFirstDayOfWeek = WeekFields.of(locale).getFirstDayOfWeek();
DayOfWeek localizedLastDayOfWeek = localizedFirstDayOfWeek.plus(6L);
try{
LocalDate shiftedWeekDate = fromDate.plusWeeks(weekOffset);
result[0] = shiftedWeekDate.with(previousOrSame(localizedFirstDayOfWeek));
result[1] = shiftedWeekDate.with(nextOrSame(localizedLastDayOfWeek));
} catch (Exception ex){
// Just add a bit more explanation for the possible RuntimeException,
// which may be thrown if the provided fromDate/weekOffset combination
// cannot be calculated.
throw new IllegalArgumentException(String.format("Shift of provided date by %d week(s) not supported!", weekOffset), ex);
}
return result;
}
public static void main(String[] args) {
for(Locale locale : Locale.getAvailableLocales()){
if(! locale.getDisplayCountry().isEmpty()){
doTest(locale);
}
}
}
private static void doTest(Locale locale){
LocalDate[] boundary;
String separator = Locale.getDefault().equals(locale) ?
"= = = = = = = = = D E F A U L T = = = = = = = ="
: "- - - - - - - - - - - - - - - - - - - - - - - -";
System.out.printf("%n%s%nIn: %s (%s)%nfirst day of week is: %s%n", separator,
locale.getDisplayCountry(), locale, WeekFields.of(locale).getFirstDayOfWeek());
LocalDate fromDate = LocalDate.now();
for (int shift = -1; shift < 2; shift++) {
boundary = getLocalizedWeekBoundary(fromDate, shift, locale);
System.out.printf("Shift %+2d => first: %s - last: %s%n", shift, boundary[0], boundary[1]);
}
}
}
public static void main(String[] args) throws Exception {
char ch;
do {
System.out.println("Press a key followed by ENTER: ");
ch = (char) System.in.read();
System.out.println("Entered: '" + ch + "' (=" + (int)ch + ")");
} while (ch != 'q');
}
interface IObserver {
void notify(Event e); //I'm a callback ;)
...
}
interface IObservable {
void register(IObserver o);
void unregister(IObserver o);
...
}
java.lang.Comparable<T> {
int compareTo(T o);
}
public class Lois {
Pitter husbend = new Pitter();
...
public class Pitter {
Lois wife = new Lois();
...
... = new Lois();
//or
... = new Pitter();
public class Main {
public static void main(String[] args) {
// You can run JVM with:
// -XX:MaxJavaStackTraceDepth=-1 (unlimited number of stack trace frames)
// -Xss4m (play around with stack size)
//
try {
first(); // causes stack overflow!
} catch (StackOverflowError e) {
System.err.println("Depth (frames):" + e.getStackTrace().length);
}
}
static int first(){
return second();
}
static int second(){
return first();
}
}
public class Lois {
Pitter myHusband = new Pitter(this);
public Lois(Pitter whoIsMyHusband){
myHusband = whoIsMyHusband;
}
//...
}
public class Pitter {
Lois myWife = new Lois(this);
public Pitter(Lois whoIsMyWife) {
myWife = whoIsMyWife;
}
// ...
}
public abstract class Pet {
String name;
int age;
int weight;
int cost;
}
...
public class Dog extends Pet {
public Dog(String name, int age){
this.name = name;
this.age = age;
}
}
...
public class Main {
public static void main(String[] args) {
Pet tuzik = new Dog("Tuzik", 5);
System.out.print(tuzik.age);
}
}
public Dog(String name, int age){...
" - это конструктор. У него нет типа. Он вызывается, когда класс инстанциируют (... = new Dog("Tuzik", 5);
) и возвращает экземпляр класса (объект). Только после этого поля объекта проинициализированны какими-то значениями. До того в них в данном примере ничего нет (точнее, там сразу после создания объекта и до отработки его конструктора везде 0 и null в name).interface IBankAccount
{
public void AddFunds(double value);
public void RemoveFunds(double value);
}
...
class BankAccount implements IBankAccount
...
class TransferManager
{
public TransferManager(IBankAccount Source, IBankAccount Destination, double Value) {
...
Виртуальня машина java это тоже интерпретатор по сути
int x; // <---- declaration *
...
x = 15; // <----- assignment
...
int y = 25; // <------- declaration, then assignment
Man superman;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Simulation {
private static final Random globalRandom = new Random(System.currentTimeMillis());
public synchronized int getRandomIntInRangeEnclosed(int min, int max){
return globalRandom.nextInt((max - min + 1) + min);
}
private final static int CUSTOMER_NUMBER = 3000;
private final static int DESK_NUMBER = 6;
public final int ITEM_DURATION_S_MIN = 3;
public final int ITEM_DURATION_S_MAX = 8;
public final CustomerFactory customerFactory = new CustomerFactory(this, CUSTOMER_NUMBER);
public final ArrayList<DeskReport> results = new ArrayList<DeskReport>(DESK_NUMBER);
public void perform(){
ExecutorService executor = Executors.newFixedThreadPool(DESK_NUMBER);
for (int i = 1; i <= DESK_NUMBER; i++) {
executor.submit(new Desk(this, i));
}
executor.shutdown();
try {
executor.awaitTermination(20, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
public void printResult(){
int maxTimeS = 0;
int maxItems = 0;
int maxCustomers = 0;
int minItems = Integer.MAX_VALUE;
int minCustomers = Integer.MAX_VALUE;
for(DeskReport r : results){
if(r.getSpentTime() > maxTimeS){
maxTimeS = r.getSpentTime();
}
if(r.getSoldItemCount() > maxItems){
maxItems = r.getSoldItemCount();
}
if(r.getSoldItemCount() < minItems){
minItems = r.getSoldItemCount();
}
if(r.getServedCustomerCount() > maxCustomers){
maxCustomers = r.getServedCustomerCount();
}
if(r.getServedCustomerCount() < minCustomers){
minCustomers = r.getServedCustomerCount();
}
}
Date date = new Date(maxTimeS * 1000L);
DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
String dateFormatted = formatter.format(date);
System.out.println("---------------- RESULTS ----------------");
System.out.println(DESK_NUMBER + " desks served " + CUSTOMER_NUMBER + " customers in " + dateFormatted);
System.out.println("Troughput min ~ max:");
System.out.println(minItems + "\t~\t" + maxItems + " \titems/desk");
System.out.println(minCustomers + "\t~\t" + maxCustomers + "\tcustomers/desk");
}
public static void main(String[] args) {
Simulation sim = new Simulation();
sim.perform();
sim.printResult();
}
}
public class CustomerFactory {
private Simulation simulation;
private int capacity = 0;
public CustomerFactory(Simulation simulation, int capacity){
this.simulation = simulation;
this.capacity = capacity;
}
public synchronized Customer getInstanceWithRandomCapacity(){
if(capacity-- > 1){
return new Customer(this.simulation.getRandomIntInRangeEnclosed(1,20));
} else {
return null;
}
}
}
public class Desk implements Runnable{
private Simulation s = null;
private int deskNo = 0;
private int servedCustomerCount = 0;
private int soldItemCount = 0;
private int spentTime = 0;
public Desk(Simulation s, int deskNo) {
this.s = s;
this.deskNo = deskNo;
}
public void run() {
System.out.println("Desk " + deskNo + " opening...");
Customer c = null;
while ((c = s.customerFactory.getInstanceWithRandomCapacity()) != null) {
servedCustomerCount++;
for(int i=c.getItemCount(); i>1; i--){
soldItemCount++;
spentTime += s.getRandomIntInRangeEnclosed(s.ITEM_DURATION_S_MIN, s.ITEM_DURATION_S_MAX);
}
//get short break after each customer ;)
sleep(Long.valueOf(s.getRandomIntInRangeEnclosed(s.ITEM_DURATION_S_MIN, s.ITEM_DURATION_S_MAX)));
}
s.results.add(new DeskReport(deskNo, servedCustomerCount, soldItemCount, spentTime));
System.out.println("Desk " + deskNo + "\tclosing.\tcustomers " + servedCustomerCount + "\titems " + soldItemCount + "\ttime(s) " + spentTime);
}
private void sleep(long ms){
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class DeskReport {
private int deskNo = 0;
private int servedCustomerCount = 0;
private int soldItemCount = 0;
private int spentTime = 0;
public DeskReport(int deskNo, int servedCustomerCount, int soldItemCount, int spentTime){
this.deskNo = deskNo;
this.servedCustomerCount = servedCustomerCount;
this.soldItemCount = soldItemCount;
this.spentTime = spentTime;
}
public int getDeskNo() {
return deskNo;
}
public int getServedCustomerCount() {
return servedCustomerCount;
}
public int getSoldItemCount() {
return soldItemCount;
}
public int getSpentTime() {
return spentTime;
}
}
public class Customer{
private int itemCount = 0;
public Customer(int itemCount){
this.itemCount = itemCount;
}
public int getItemCount(){
return this.itemCount;
}
}