×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Added: Mar 7, 2021 12:01 PM
Modified: Mar 7, 2021 6:16 PM
Views: 4759
Tags: oo
  1. //Main
  2. package com.company;
  3.  
  4. public class Main {
  5.  
  6.     public static void main(String[] args) {
  7.         //Creating Objects
  8.         //New is used to allocate memory in the system
  9.         //Values are being assigned
  10.         Car ferrari;
  11.         ferrari = new Car();
  12.         ferrari.model = "Ferrari F430";
  13.         ferrari.seats = 4;
  14.         ferrari.color = "Red";
  15.  
  16.         ferrari.display();
  17.         //Car is being used like a datatype
  18.  
  19.         Car tesla = new Car();
  20.         tesla.model = "Model S";
  21.         tesla.seats = 4;
  22.         tesla.color = "Black";
  23.         tesla.display();
  24.  
  25.         Car audi = new Car();
  26.         audi.model = "Audi SQ5";
  27.         audi.color = "Blue";
  28.         audi.seats = 4;
  29.         audi.display();
  30.  
  31.  
  32.         //Object declaration and memory allocation
  33.         Car test; //no memory allocated yet, if you use it right now, it will print out an error
  34.         test = new Car(); //memory allocated and assigned to test
  35.  
  36.         //With "new": a reference will be created, actual memory will be allocated with all the variables inside the object
  37.  
  38.     }
  39. }
  40.  
  41.  
  42. //Car
  43. package com.company;
  44.  
  45. public class Car {
  46.  
  47.     //Eigenschaften
  48.     public String model;
  49.     public String color;
  50.     public int seats;
  51.  
  52.     //Blueprint
  53.     public void display(){
  54.         System.out.println("Model is : " + model);
  55.         System.out.println("Color is : " + color);
  56.         System.out.println("Seats is : " + seats);
  57.     }
  58.  
  59. }
  60.