how to call a class in java code example
Example 1: how to call a function from a class java
public class Classroom {
private String teacherName;
public Classroom(String teacherName){
this.teacherName = teacherName;
}
public String getTeacherName() {
return teacherName;
}
}
public static void main(String[] args){
Classroom firstGrade = new Classroom("John");
firstGrade.getTeacherName();
}
Example 2: java use method in another class
class A {
public void a1 ( ) {
}
private void a2 ( ) {
}
}
class B {
private A objA = new A ( );
public void b1 ( ) {
objA.a1 ();
}
void b2 ( ) {
objA.a2 ();
}
}
Example 3: using class in java
public class HelloWorld {
public static void main(String[] args) {
class Number{
int number;
public boolean isPos(){
if(number > 0){
return true;
} else {
return false;
}
}
}
Number myNumber = new Number();
myNumber.number = 7;
if(myNumber.isPos()){
System.out.println(myNumber.number + " is positive!!!");
} else {
System.out.println(myNumber.number + " is not positive!!!");
}
}
}
Example 4: using class in java
public class HelloWorld {
public static void main(String[] args) {
class User{
int score;
public boolean hasWon(){
if(score >= 100){
return true;
} else {
return false;
}
}
}
User dave = new User();
dave.score = 20;
System.out.println(dave.hasWon());
}
}