Java Core Concepts with Runnable Code Examples
1. Classes and Objects
class Car {
String brand = "Skoda";
int speed = 180;
void display() {
System.out.println("Brand: " + brand + ", Speed: " + speed);
}
public static void main(String[] args) {
Car myCar = new Car(); // Object creation
myCar.display();
}
}
2. Methods
class Calculator {
int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
int result = calc.add(10, 15);
System.out.println("Sum: " + result);
}
}
3. Constructors - Default
class Bike {
Bike() {
System.out.println("Bike created using default constructor.");
}
public static void main(String[] args) {
Bike b = new Bike();
}
}
3. Constructors - Parameterized
class Bike {
String model;
Bike(String m) {
model = m;
}
Java Core Concepts with Runnable Code Examples
void display() {
System.out.println("Model: " + model);
}
public static void main(String[] args) {
Bike b = new Bike("Duke 390");
b.display();
}
}
3. Constructors - Copy
class Bike {
String model;
Bike(String m) {
model = m;
}
Bike(Bike b) {
model = b.model;
}
void display() {
System.out.println("Model: " + model);
}
public static void main(String[] args) {
Bike b1 = new Bike("Interceptor");
Bike b2 = new Bike(b1);
b2.display();
}
}
4. Method Overloading
class Print {
void show(int a) {
System.out.println("Integer: " + a);
}
void show(String s) {
System.out.println("String: " + s);
}
public static void main(String[] args) {
Print p = new Print();
p.show(10);
p.show("Java");
Java Core Concepts with Runnable Code Examples
}
}
5. Inheritance - Single
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
public static void main(String[] args) {
Dog d = new Dog();
d.sound();
d.bark();
}
}
5. Inheritance - Multilevel
class Animal {
void eat() {
System.out.println("Animal eats");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
class Puppy extends Dog {
void weep() {
System.out.println("Puppy weeps");
}
public static void main(String[] args) {
Puppy p = new Puppy();
p.eat();
p.bark();
p.weep();
}
}
Java Core Concepts with Runnable Code Examples
5. Inheritance - Hierarchical
class Animal {
void breathe() {
System.out.println("Animal breathes");
}
}
class Cat extends Animal {
void meow() {
System.out.println("Cat meows");
}
}
class Bird extends Animal {
void fly() {
System.out.println("Bird flies");
}
public static void main(String[] args) {
Cat c = new Cat();
c.breathe();
c.meow();
Bird b = new Bird();
b.breathe();
b.fly();
}
}
6. Runtime Polymorphism (Method Overriding)
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
public static void main(String[] args) {
Animal a = new Dog(); // upcasting
a.sound(); // runtime polymorphism
}
}