Skip to content

Commit 2846e54

Browse files
committed
Interfaces Example
1 parent 47cc601 commit 2846e54

2 files changed

Lines changed: 38 additions & 0 deletions

File tree

Interfaces/ExInterface.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package BasicJavaPrograms.Interfaces;
2+
interface Animal {
3+
int eyes = 2; // All variables in an interface are public, static and final by default, so we don't need to use the abstract, public, static and final keywords here.
4+
void walk();
5+
// Cannot have a constructor in an interface because we cannot create an object of an interface. We can only create an object of a class that implements the interface.
6+
// All methods in an interface are abstract by default, so we don't need to use the abstract keyword here. Also, we cannot have a method body in an interface method.
7+
}
8+
interface Herbivore {
9+
void eatGrass();
10+
}
11+
class Horse implements Animal {
12+
public void walk() {
13+
System.out.println("Walks on 4 legs");
14+
}
15+
}
16+
public class ExInterface {
17+
public static void main(String[] args) {
18+
Horse horse = new Horse();
19+
horse.walk();
20+
}
21+
}

Interfaces/StudentInterface.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package BasicJavaPrograms.Interfaces;
2+
class Student{
3+
String name;
4+
static String school;
5+
// Static variables and methods belong to the class rather than to any specific instance of the class. This means that they can be accessed without creating an object of the class. In this example, we can access the static variable 'school' using the class name 'Student.school' without creating an object of the Student class.
6+
public static void changeSchool(String newSchool){
7+
school = newSchool;
8+
}
9+
}
10+
public class StudentInterface {
11+
public static void main(String[] args) {
12+
Student.school = "DSRV School";
13+
Student student1 = new Student();
14+
student1.name = "Atharv";
15+
System.out.println(Student.school);
16+
}
17+
}

0 commit comments

Comments
 (0)